静态数据时有效合并

时间:2017-03-29 21:11:34

标签: r merge

我在数据框static_data中存储了一些静态数据。目标是将datastatic_data合并,以获得output

data <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"))

static_data <- data.frame(I=c("a","b","c","d","e"),Info=c(1,2,3,4,5))

output <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"),
                     AI=c(1,2,3,4,5),BI=c(1,2,2,5,5))

我的代码如下

colnames(data) <- c("I","B")
temp <- merge(data, static_data,by="I)

等等。什么是拥有高效代码的最佳方式?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

mg <- merge(data, static_data, by.x = "A", by.y = "I")
cbind(mg, BI=merge(data, static_data, by.x = "B", by.y = "I")[,3])

#  A B Info BI
#1 a a    1  1
#2 b b    2  2
#3 c b    3  2
#4 d e    4  5
#5 e e    5  5