stack 2 df with different column name

How to stack 2 data frames with different column name and column number? I have 2 data frame below and want to keep all rows and columns. Put null values in column that column name are not identical in both df or columns are in one data frame only. I used rbind() and gave me error message like names not match ... Any suggestion? Thanks in advance!

df1<-data.frame(team=c('A', 'A', 'B'),
pos=c('X', 'F', 'F'),
points=c(128, 222, 129))
df1
df2<- data.frame(team=c('A', 'B', 'C'),
position=c('X', 'F', 'G'),
assists=c(224, 428, 466))
df2

df3 <- rbind(df1, df2)

Try bind_rows from dplyr.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df1<-data.frame(team=c('A', 'A', 'B'),
                pos=c('X', 'F', 'F'),
                points=c(128, 222, 129))
df1
#>   team pos points
#> 1    A   X    128
#> 2    A   F    222
#> 3    B   F    129
df2<- data.frame(team=c('A', 'B', 'C'),
                 position=c('X', 'F', 'G'),
                 assists=c(224, 428, 466))
df2
#>   team position assists
#> 1    A        X     224
#> 2    B        F     428
#> 3    C        G     466
df3 <- bind_rows(df1, df2)
df3
#>   team  pos points position assists
#> 1    A    X    128     <NA>      NA
#> 2    A    F    222     <NA>      NA
#> 3    B    F    129     <NA>      NA
#> 4    A <NA>     NA        X     224
#> 5    B <NA>     NA        F     428
#> 6    C <NA>     NA        G     466

Created on 2022-12-05 with reprex v2.0.2

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.