r语言 - 如何排序具有特定值的变量在数据集中的每第x个位置?



基本上,我试图弄清楚如何移动所有行,其中动画变量中的值是1到数据集中每12个位置。在给定的示例数据中,每个animation = 1的游戏(游戏13和17)必须位于列表中的第12行。我可以手动完成,但这需要应用于更广泛的数据集。

Game    Score   Animated
10      474     0
11      2902    0
12      4128    0
13      877     1
14      576     0
15      71      0
16      3217    0
17      1046    1
18      2232    0
19      20      0
20      151     0
21      133     0
22      4524    0
23      87      0
24      18      0
25      114     0
26      6       0
27      94      0
28      83      0
29      248     0
30      8       0
31      66      0
32      87      0
33      41      0
34      181     0
35      17      0
36      50      0

那么,它应该是这样的:

Game    Score   Animated
10      474     0
11      2902    0
12      4128    0
14      576     0
15      71      0
16      3217    0
18      2232    0
19      20      0
20      151     0
21      133     0
22      4524    0
13      877     1
23      87      0
24      18      0
25      114     0
26      6       0
27      94      0
28      83      0
29      248     0
30      8       0
31      66      0
32      87      0
33      41      0
17      1046    1
34      181     0
35      17      0
36      50      0

游戏13在列表中移至第12位,游戏17移至第24位,我需要以相同的方式对数据集的其余部分进行排序。

这样如何:

dat <- tibble::tribble(~Game,    ~Score,   ~Animated,
10,      474,     0,
11,      2902,    0,
12,      4128,    0,
13,      877,     1,
14,      576,     0,
15,      71,      0,
16,      3217,    0,
17,      1046,    1,
18,      2232,    0,
19,      20,      0,
20,      151,     0,
21,      133,     0,
22,      4524,    0,
23,      87,      0,
24,      18,      0,
25,      114,     0,
26,      6,       0,
27,      94,      0,
28,      83,      0,
29,      248,     0,
30,      8,       0,
31,      66,      0,
32,      87,      0,
33,      41,      0,
34,      181,     0,
35,      17,      0,
36,      50,      0)

which_animated <- which(dat$Animated == 1)
others <- setdiff(1:nrow(dat), which_animated)
animated_obs <- seq(12, nrow(dat), by=12)[1:length(which_animated)]
other_obs <- 1:nrow(dat)
other_obs <- setdiff(other_obs, animated_obs)
new_obs <- rep(NA, nrow(dat))
new_obs[which_animated] <- animated_obs
new_obs[others] <- other_obs
sorted_dat <- dat[order(new_obs), ]

sorted_dat[c(12,24), ]
# # A tibble: 2 x 3
#   Game Score Animated
#   <dbl> <dbl>    <dbl>
# 1    13   877        1
# 2    17  1046        1

最新更新