简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM