[英]Is there a way in R to combine columns based on a names column (0s involved)
I'm trying to combine a few columns.我正在尝试合并几列。 Consider these.
考虑这些。
Name![]() |
Age![]() |
---|---|
Amy![]() |
21 ![]() |
Jake![]() |
15 ![]() |
Bill![]() |
24 ![]() |
Sophie![]() |
30 ![]() |
Name![]() |
Children![]() |
---|---|
Amy![]() |
2 ![]() |
Bill![]() |
1 ![]() |
Name![]() |
Pets![]() |
---|---|
Jake![]() |
1 ![]() |
The desired output is:所需的 output 是:
Name![]() |
Age![]() |
Children![]() |
Pets![]() |
50 more columns...![]() |
---|---|---|---|---|
Amy![]() |
21 ![]() |
2 ![]() |
0 ![]() |
... ![]() |
Jake![]() |
15 ![]() |
0 ![]() |
1 ![]() |
... ![]() |
Bill![]() |
24 ![]() |
1 ![]() |
0 ![]() |
... ![]() |
Sophie![]() |
30 ![]() |
0 ![]() |
0 ![]() |
... ![]() |
Note that I've got about 50 columns of different characteristics to combine, hence merge and cbind have caused me tremendous issues.请注意,我有大约 50 列不同的特征要组合,因此 merge 和 cbind 给我带来了巨大的问题。
df4<-merge(merge(df1, df2, all.x = TRUE), df3, all.x = TRUE)
df4[is.na(df4)] <-0
df4
Name Age Children Pets
1 Amy 21 2 0
2 Bill 24 1 0
3 Jake 15 0 1
4 Sophie 30 0 0
Note that if you have many dfs, you could do:请注意,如果你有很多 dfs,你可以这样做:
my_list <- list(df1, df2, df3, df4, ...)
Reduce(function(...)merge(..., all.x = TRUE), my_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.