我需要一种合并和扩展两个数据框的方法。因此,在此简化示例中,我需要合并type
并展开plot
,以便它出现在新数据帧的每一行中,并与type
匹配。下面的示例输出仅提供给df1的前2行,但此示例中的最终dataFrame应该具有50行。有没有简单的方法可以做到这一点?
数据:
type <- c("control","treat","treat","control","control")
plot <- c(1,2,3,4,5)
df1 <- data.frame(plot, type)
bands <- c(seq(1,10),seq(1,10))
otherInfo <- rep("stuff", 20)
otherInfo2 <- rep("things",20)
type <- c(rep("control",10),rep("treat",10))
df2 <- data.frame(bands, otherInfo, otherInfo2, type)
dataFrame1:
plot type
1 control
2 treat
3 treat
4 control
5 control
dataFrame2:
bands otherInfo otherInfo2 type
1 stuff things control
2 stuff things control
3 stuff things control
4 stuff things control
5 stuff things control
6 stuff things control
7 stuff things control
8 stuff things control
9 stuff things control
10 stuff things control
1 stuff things treat
2 stuff things treat
3 stuff things treat
4 stuff things treat
5 stuff things treat
6 stuff things treat
7 stuff things treat
8 stuff things treat
9 stuff things treat
10 stuff things treat
dataFrame3(所需输出)
bands otherInfo otherInfo2 type plot
1 stuff things control 1
2 stuff things control 1
3 stuff things control 1
4 stuff things control 1
5 stuff things control 1
6 stuff things control 1
7 stuff things control 1
8 stuff things control 1
9 stuff things control 1
10 stuff things control 1
1 stuff things treat 2
2 stuff things treat 2
3 stuff things treat 2
4 stuff things treat 2
5 stuff things treat 2
6 stuff things treat 2
7 stuff things treat 2
8 stuff things treat 2
9 stuff things treat 2
10 stuff things treat 2
etc...
答案 0 :(得分:1)
df3 = do.call(rbind, lapply(split(df2, df2$bands), function(x)
merge(x, df1, by = "type", all = TRUE)))
NROW(df3)
# [1] 50
如果这很重要,您可能必须进一步对行进行重新排序。