r语言 - 过滤包含列表值的行



我正在使用RStudio,我有一个包含候选人列表的数据框,和一个包含每个投票地点和候选人的所有投票的数据框。

我只想提取包含此列表中候选人投票的行。

的例子:

  • :

    Candidate
    A
    B
    D
    G
    
  • 选票:

    Candidate       Number of Votes
    A               124
    B               52
    C               13
    D               62
    E               33
    F               7
    G               67
    

我想创建一个新的数据框架,其中只包含"列表"的候选人和投票:

  • 候选名单投票:

    Candidate       Number of Votes
    A               124
    B               52
    D               62
    G               67
    

这个例子是一个简化。我的数据库包含超过30000个"候选人">

Thanks in advance

我们可以在base R中使用subset

subset(Votes, Candidate %in% List$Candidate)

可以用merge()合并两个数据帧:

merge(df1, df2, by = "Candidate", all.x = TRUE)

或者

dplyr::left_join(df1, df2, by = "Candidate")
#   Candidate Number_of_Votes
# 1         A             124
# 2         B              52
# 3         D              62
# 4         G              67

数据
df1 <- structure(list(Candidate = c("A", "B", "D", "G")), class = "data.frame", row.names = c(NA, -4L))
df2 <- structure(list(Candidate = c("A", "B", "C", "D", "E", "F", "G"),
Number_of_Votes = c(124L, 52L, 13L, 62L, 33L, 7L, 67L)), class = "data.frame", row.names = c(NA, -7L))

最新更新