我有一个数据文件,每个参与者一行(根据他们参加的研究,命名为1-x)。我想检查数据集中是否存在所有参与者。这是我的玩具数据集,personid是参与者,研究是他们参与的研究。

df <- read.table(text = "personid study measurement
1         x     23
2         x     32
1         y     21
3         y     23
4         y     23
6         y     23", header=TRUE)


看起来像这样:

  personid study measurement
1        1    x          23
2        2    x          32
3        1    y          21
4        3    y          23
5        4    y          23
6        6    y          23


所以对于y,我缺少参与者2和5。如何自动检查?我尝试添加一个计数器变量并将该计数器变量与参与者ID进行比较,但是一旦缺少一个参与者,由于对齐方式已关闭,因此比较是没有意义的。

df %>% group_by(study) %>% mutate(id = 1:n(),check = id==personid)
Source: local data frame [6 x 5]
Groups: date [2]

  personid   study measurement    id check
     <int> <fctr>       <int> <int> <lgl>
1        1      x          23     1  TRUE
2        2      x          32     2  TRUE
3        1      y          21     1  TRUE
4        3      y          23     2 FALSE
5        4      y          23     3 FALSE
6        6      y          23     4 FALSE

最佳答案

假设您的personid是顺序的,那么您可以使用setdiff进行此操作,即

library(dplyr)

df %>%
 group_by(study) %>%
 mutate(new = toString(setdiff(max(personid):min(personid), personid)))

#Source: local data frame [6 x 4]
#Groups: study [2]

#  personid  study measurement   new
#     <int> <fctr>       <int> <chr>
#1        1      x          23
#2        2      x          32
#3        1      y          21  5, 2
#4        3      y          23  5, 2
#5        4      y          23  5, 2
#6        6      y          23  5, 2

10-02 07:03
查看更多