简体   繁体   中英

Combine two dataframe in R

I have two data frames.

df1 <- data.frame(cbind(c(2,3),c(4,5)))
df2 <- data.frame(cbind(c(1,2,6),c(9,8,7)))

I want to combine them and the result is like:

df3 <- data.frame(cbind(c(2,2,2,3,3,3), c(4,4,4,5,5,5),c(1,2,6,1,2,6), c(9,8,7,9,8,7)))

Is there any method to do this? Thanks.

In base R, you can use merge and join them by NULL to get a cartesian product of two dataframes.

merge(df1, df2, by = NULL)

#  X1.x X2.x X1.y X2.y
#1    2    4    1    9
#2    3    5    1    9
#3    2    4    2    8
#4    3    5    2    8
#5    2    4    6    7
#6    3    5    6    7

Use crossing

library(tidyr)
crossing(df1, setNames(df2, paste0(names(df2), "_1")))

-ouptut

# A tibble: 6 x 4
     X1    X2  X1_1  X2_1
  <dbl> <dbl> <dbl> <dbl>
1     2     4     1     9
2     2     4     2     8
3     2     4     6     7
4     3     5     1     9
5     3     5     2     8
6     3     5     6     7

Or with expand_grid

expand_grid(df1, df2, .name_repair = "unique")

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