r - 如何将具有特定值的变量排序到数据集中的每个第 x 个位置?
问题描述
基本上,我试图弄清楚如何将 Animated 变量中的值为 1 的所有行移动到数据集中的每 12 个位置。在给定的示例数据中,Animated = 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
推荐阅读
- java - Gson 不使用对象的默认字段值(不是原语)
- apache - 使用 mod_rewrite 从 URL 中删除 _escaped_fragment
- sql-server - 单击取消时查询继续执行,然后说行受到影响
- sql - 如何使用插件在 WordPress 数据库中创建表
- powershell - Powershell等效于批处理命令“START”以使用映射驱动器打开窗口
- python - Python / rq - 如何将信息从调用者传递给工作人员?
- java - 在thymeleaf中获取java对象
- azure - 主机串行端口转发到 Azure VM 客户端
- c - C 指针(总是)是否以有效的地址存储器开头?
- python - 使用python检查数据库连接是否繁忙