我在数据框static_data
中存储了一些静态数据。目标是将data
与static_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)
等等。什么是拥有高效代码的最佳方式?
答案 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