R 列出数据集中某列的值和另一列的所有值

R 列出数据集中某列的值和另一列的所有值,r,R,奇怪的标题,这是我的情况:我正在处理纵向数据,我想列出所有参加过所有可用调查的受访者。例如,考虑这些数据: respondent <- c(rep(1, 3), 2, rep(3, 3), rep(4, 2)) survey <- c(1:3, 1, 1:3, 2:3) survey.respondent <- data.table(respondent, survey) # respondent survey # 1: 1 1 # 2:

奇怪的标题,这是我的情况:我正在处理纵向数据,我想列出所有参加过所有可用调查的受访者。例如,考虑这些数据:

respondent <- c(rep(1, 3), 2, rep(3, 3), rep(4, 2))
survey <- c(1:3, 1, 1:3, 2:3)
survey.respondent <- data.table(respondent, survey)
#    respondent  survey
# 1:          1       1
# 2:          1       2
# 3:          1       3
# 4:          2       1
# 5:          3       1
# 6:          3       2
# 7:          3       3
# 8:          4       2
# 9:          4       3
试一试

或者您可以使用

  indx <- !rowSums(!table(survey.respondent))
  names(indx)[indx]
  #[1] "1" "3"
indx试试这个(我只是把
survey.responder
重命名为
df
,因为这是一个很长的名字。)


当然,将以下解决方案封装在函数中并不难——我意识到我可能需要在两个变量上完成这项工作,因此,我将很快尝试+microbenchmark your和@collone beuvel的答案,并标记出最快的答案。两人都投了赞成票-谢谢你的快速回答!当然,我使用了
data.table
方法,因为您已经拥有了该对象。如果您正在进行基准测试,则使用
.I
而不是
.SD
,并提取
V1
 res <- survey.respondent[, .SD[all(unique(survey.respondent$survey) %in% 
                     unique(survey))], by = respondent]
 res
 #   respondent survey
 #1:          1      1
 #2:          1      2
 #3:          1      3
 #4:          3      1
 #5:          3      2
 #6:          3      3

 unique(res$respondent)
 #[1] 1 3
 res <- survey.respondent[survey.respondent[,
       .I[all(unique(survey.respondent$survey) %in% 
           unique(survey))], by = respondent]$V1]
  indx <- !rowSums(!table(survey.respondent))
  names(indx)[indx]
  #[1] "1" "3"
df = survey.respondent

Reduce(intersect, lapply(unique(df$survey), function(u) df[survey==u,]$respondent))
#[1] 1 3