查找两个数据帧的匹配元素并分配新值

时间:2015-07-06 16:22:39

标签: r dataframe matching

我有两个数据框,我想找到匹配的元素。然后我想根据匹配元素为其中一个数据帧分配一个新值。设计数据框如下所示:

master

它有240行和5列。条件数据框具有60,000行和与设计数据帧相同的前4列。条件df的每一行与设计df中的一行匹配(不包括最后一列)。我想将CondNum从设计df分配给条件数据框中的匹配行。例如,条件数据如下所示:

   ss clusters  ICC items CondNum
1 300       10 0.05    10       1
2 300       10 0.05    20       2
3 300       10 0.05    50       3
4 300       10 0.05    70       4
5 300       10 0.10    10       5

...
235 5000      150 0.3    50     235
236 5000      150 0.3    70     236
237 5000      150 0.4    10     237
238 5000      150 0.4    20     238
239 5000      150 0.4    50     239
240 5000      150 0.40   70     240

我想在条件df中添加一列,并将条件df中的CondNum值分配给条件df中的匹配元素。我无法找到这个具体问题的答案。所以最终的结果应该是这样的:

    ss clusters   ICC items
1 1000       10 0.053    10
2 1000       10 0.053    10
3 1000       10 0.053    10
4 300        10  0.10    20
...
51,998 5000      100 0.4    20     
51,999 5000      100 0.4    20    

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用left_join中的dplyr

> design
#   ss clusters  ICC items CondNum
#1 300       10 0.05    10       1
#2 300       10 0.05    20       2
#3 300       10 0.05    50       3
#4 300       10 0.05    70       4
#5 300       10 0.10    10       5

> condition
#    ss clusters  ICC items
#1  300       10 0.05    20
#2  300       10 0.05    50
#3 1000       10 0.05    70
#4  300       10 0.10    10

> dplyr::left_join(condition, design)
#Joining by: c("ss", "clusters", "ICC", "items")
#    ss clusters  ICC items CondNum
#1  300       10 0.05    20       2
#2  300       10 0.05    50       3
#3 1000       10 0.05    70      NA
#4  300       10 0.10    10       5

或者根据评论中提到的,您可以使用基础R中的merge()

> merge(condition, design, all.x = TRUE)
#    ss clusters  ICC items CondNum
#1  300       10 0.05    20       2
#2  300       10 0.05    50       3
#3  300       10 0.10    10       5
#4 1000       10 0.05    70      NA

注意:我为了示例的目的修改了数据集

数据

## design
design <- structure(list(ss = c(300L, 300L, 300L, 300L, 300L), clusters = c(10L, 
10L, 10L, 10L, 10L), ICC = c(0.05, 0.05, 0.05, 0.05, 0.1), items = c(10L, 
20L, 50L, 70L, 10L), CondNum = 1:5), .Names = c("ss", "clusters", 
"ICC", "items", "CondNum"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

## condition
condition <- structure(list(ss = c(300L, 300L, 1000L, 300L), clusters = c(10L, 
10L, 10L, 10L), ICC = c(0.05, 0.05, 0.05, 0.1), items = c(20L, 
50L, 70L, 10L)), .Names = c("ss", "clusters", "ICC", "items"), 
class = "data.frame", row.names = c("1", "2", "3", "4"))