奇怪的标题,这是我的情况:我正在处理纵向数据,并想列出所有已参加所有可用调查的受访者。例如考虑这个数据:
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
在这种情况下,我想选择受访者 1 和 3,因为他们是调查 1、2 和 3 中的两个人。对于有限数量的调查,一个循环就足够了,但我想这适用于任意数量的调查。
所以理想情况下我有一个像
这样的函数f(col1, col2) { ... }
f(respondent, survey) # Would return c(1, 3) in this case
# Or alternatively
f(dt, col1, col2) { ... } # Presumably data.table would work best
f(survey.respondent, "respondent", "survey") # c(1, 3)
最佳答案
尝试
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
或者更快的方法是使用 .I
res <- survey.respondent[survey.respondent[,
.I[all(unique(survey.respondent$survey) %in%
unique(survey))], by = respondent]$V1]
或者你可以使用table
indx <- !rowSums(!table(survey.respondent))
names(indx)[indx]
#[1] "1" "3"
关于r - 列出数据集中存在的列的值以及另一列的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625288/