将数据从一个数据帧提取到另一个具有不同行长度的数据帧
我有两个 data.frames,如下:
df1 <- data.frame(A=c("lee","eeu","ees"), B=c("lee","ggu","1su"), C=c(1,1,1)
A B C
1 lee lee 1
2 eeu ggu 1
3 ees 1su 1
df2 <- data.frame (X=c("lee","1su","eeu","ggu"), Y=c("3k3","4k4","5k","2ee"), Z=c("ggg","","","ooo"), ZA=c("vvv","","",""))
X Y Z ZA
1 lee 3k3 ggg vvv
2 1su 4k4
3 eeu 5k
4 ggu 2ee ooo
我想通过将 df1$B 与 df2$X 匹配来扩展 df1。当 df1$B = df2$X 时,我想向 new_df1 添加额外的行,其中 new B = df2 中同一行的其他条目,但保持 A 和 C 相同。
new_df1预计如下:
A B C
lee 3k3 1 ### df1$B1= df2$X1= lee
lee ggg 1
lee vvv 1
eeu 2ee 1 ### df1$B2= df2$X4= ggu
eeu ooo 1
ees 4k4 1 ### df1$B3= df2$X2= lsu
我过去使用lapply的经验似乎对内存要求很高,是否可以不使用lapply来完成?
I have two data.frames as follows:
df1 <- data.frame(A=c("lee","eeu","ees"), B=c("lee","ggu","1su"), C=c(1,1,1)
A B C
1 lee lee 1
2 eeu ggu 1
3 ees 1su 1
df2 <- data.frame (X=c("lee","1su","eeu","ggu"), Y=c("3k3","4k4","5k","2ee"), Z=c("ggg","","","ooo"), ZA=c("vvv","","",""))
X Y Z ZA
1 lee 3k3 ggg vvv
2 1su 4k4
3 eeu 5k
4 ggu 2ee ooo
I want to expand df1 by matching df1$B with df2$X. When df1$B = df2$X, I want to add additional rows to the new_df1 with new B = other entries in df2 on the same row, but keeping A and C the same.
new_df1 is expected to be as follows:
A B C
lee 3k3 1 ### df1$B1= df2$X1= lee
lee ggg 1
lee vvv 1
eeu 2ee 1 ### df1$B2= df2$X4= ggu
eeu ooo 1
ees 4k4 1 ### df1$B3= df2$X2= lsu
My past experience on using lapply seems to be very memory-demanding, is it possible to be done without using lapply?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你想要的是这个的子集:
我将该对象分配给“M1”(后来注意到它不需要 all=TRUE)
I think what you wnat is a subset of this:
I assigned that object to "M1" (and later noticed that it did not need all=TRUE)
我将使用 reshape 包中的 Melt() 来完成此任务。
现在子集和 rbind()
I would use melt() from the reshape package for this task.
Now subset, and rbind()
有更简单的方法可以做到这一点...使用
match
函数。您也可以将其扩展到其他列。
There is much better easy to do this...use the
match
function.You can expand it to other columns too.