Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用随机位置的预定义值填充向量_R_Dplyr - Fatal编程技术网

R 用随机位置的预定义值填充向量

R 用随机位置的预定义值填充向量,r,dplyr,R,Dplyr,我有一列球员和指标给我,哪一个是第一。指示器可以随机指向任何玩家。顺序总是正确的,所以结果将从指示器向下,然后从向上,直到指示器再次出现。结果栏是我要找的。也可以有不同数量的玩家。所以在本例中,player4是第一个,player3是最后一个 如何动态填写结果栏,并了解指标点,使其始终正确 library(dplyr) x <- c(6, 7, 8, 1, 2, 3, 4, 5) pos <- c(NA, NA, NA, "Y", NA, NA, NA, NA

我有一列球员和指标给我,哪一个是第一。指示器可以随机指向任何玩家。顺序总是正确的,所以结果将从指示器向下,然后从向上,直到指示器再次出现。结果栏是我要找的。也可以有不同数量的玩家。所以在本例中,player4是第一个,player3是最后一个

如何动态填写结果栏,并了解指标点,使其始终正确

library(dplyr)

x <- c(6, 7, 8, 1, 2, 3, 4, 5)
pos <-  c(NA, NA, NA, "Y", NA, NA, NA, NA)
y <- paste0("player", 1:8)

tibble(player = y,
       pos = pos,
       result = x)
    
# A tibble: 8 x 3
  player  pos   result
  <chr>   <chr>  <dbl>
1 player1 NA         6
2 player2 NA         7
3 player3 NA         8
4 player4 Y          1
5 player5 NA         2
6 player6 NA         3
7 player7 NA         4
8 player8 NA         5
库(dplyr)

x

库(tidyverse)
x#A tibble:8 x 5
#>播放器pos结果tmp out
#>          
#>1名球员16 6
#>2玩家2 7 7
#>3玩家3 8 8
#>4播放器4 Y 1 Y 1
#>5播放器5 2 Y 2
#>6播放器6 3 Y 3
#>7播放者7 4 Y 4
#>8播放器8 5 Y 5

df%>%
突变(tmp=pos)%>%
填充(tmp,.direction=“down”)%>%
变异(out=ifelse(cumsum(!is.na(tmp))==0,行数()+max(cumsum(!is.na(tmp))),cumsum(!is.na(tmp)))%>%
选择(-tmp)
#>#A tibble:8 x 4
#>播放机pos结果输出
#>         
#>1名球员16 6
#>2玩家2 7 7
#>3玩家3 8 8
#>4播放器4 Y 1 1
#>5玩家5 2 2
#>6玩家6 3 3
#>7玩家7 4 4
#>8玩家8 5 5
由(v1.0.0)于2021年1月31日创建

df %>% 
  mutate(tmp = pos) %>% 
  fill(tmp, .direction = "down") %>% 
  mutate(out = ifelse(cumsum(!is.na(tmp)) == 0, row_number() + max(cumsum(!is.na(tmp))), cumsum(!is.na(tmp)))) %>% 
  select(-tmp)
#> # A tibble: 8 x 4
#>   player  pos   result   out
#>   <chr>   <chr>  <dbl> <int>
#> 1 player1 <NA>       6     6
#> 2 player2 <NA>       7     7
#> 3 player3 <NA>       8     8
#> 4 player4 Y          1     1
#> 5 player5 <NA>       2     2
#> 6 player6 <NA>       3     3
#> 7 player7 <NA>       4     4
#> 8 player8 <NA>       5     5