使用r为每个人选择第五行

时间:2016-12-27 17:43:39

标签: r select row

我的数据框如下所示:

ID    x1    x2
1     23    12
1     13    9
1     ..    ..
1
1
1
1
...
2
2
2
2
2
2
...

对个体进行重复测量。我想通过仅选择每个人的第五个观察来生成数据帧。这似乎很容易,但我无法弄清楚正确的方法。谢谢你的帮助......

3 个答案:

答案 0 :(得分:3)

基础R中的一种方法是直接使用split-apply-combine概念。首先split将data.frame分配到ID的data.frames列表中。其次,使用lapply[从每个data.frame中拉出第五行,最后将rbind结果与do.call一起拉出。

do.call(rbind, lapply(split(df, df$id), function(x) x[5,]))
  id values
a  a      5
b  b      5
c  c      5
d  d      5
e  e      5
f  f      5
g  g      5

构建val列的值以表示行号。

数据

df <- data.frame(id=rep(letters[1:7], each=10), values=rep(1:10))

答案 1 :(得分:2)

我们可以使用slice

中的dplyr
library(dplyr)
df1 %>%
   group_by(ID) %>%
   slice(5)

答案 2 :(得分:2)

使用data.table的另一种方法是

library(data.table)    
setDT(df)[, .SD[5], by=ID]