'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:
| 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.
Solution 1:[1]
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:
my_list <- list(df1, df2, df3, df4, ...)
Reduce(function(...)merge(..., all.x = TRUE), my_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
