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:          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/

相关文章:

从 data.table 中删除一列相同但另一列不同的行

r - 为什么使用 NGramTokenizer 时 R 会挂起?

r - 连接到 R 中的 redis 集群

r - 使用 integral() 函数时发生变异的 dplyr 错误 "length(xmin) == 1 is not TRUE"

python - 用 Pandas : Is there an equivalent to dplyr's select(. ..,一切())重新排列列?

只有在我连接到我的工作 VPN 后,R Studio 才会非常慢?

R 和矩阵 1 行

r - 如何查找用于编译 R 的编译器

R 和 ifelse 函数

R - 使用 ggplot2- 和 raster-packages 地理引用光栅图像的原始颜色