0

Is there a way to stack dataframes in a row wise fashion. Consider the following code

motors <- c("audi", "honda", "ford")
age <- c(1, 2, 3)

motors1 <- motors
age1 <- c(2, 3, 1)

dat1 <- data.frame(motors, age)
dat2 <- data.frame(motors1, age1)

I would like to perform a rbind() type operation on dat1 and dat2 but this wont work as "motors" column in dat1 and "motors2" in dat2 are different.

Is there a way to perform this operation the to combine the two dataframes into 1 so there is still 2 columns of data but 8 rows of data (including column names).

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
TheBoomerang
  • 109
  • 5

2 Answers2

3

Set the names of dat2 to those of dat1 and include the names of dat1 and 2 in it.

rbind(rbind(names(dat1), dat1), setNames(rbind(names(dat2), dat2), names(dat1)))
#   motors  age
#1  motors  age
#2    audi    1
#3   honda    2
#4    ford    3
#5 motors1 age1
#6    audi    2
#7   honda    3
#8    ford    1

In case just to stack it without including the colnames either rename the colnames or use c in Map and convert it in a data.frame with list2DF.

rbind(dat1, setNames(dat2, names(dat1)))
#  motors age
#1   audi   1
#2  honda   2
#3   ford   3
#4   audi   2
#5  honda   3
#6   ford   1

list2DF(Map(c, dat1, dat2))
#  motors age
#1   audi   1
#2  honda   2
#3   ford   3
#4   audi   2
#5  honda   3
#6   ford   1

Have also a look at rbind dataframes with a different column name and Simplest way to get rbind to ignore column names.

GKi
  • 37,245
  • 2
  • 26
  • 48
1

I use mapply to quickly combine data in these situations:

mapply(c, dat1, dat2)

Though it returns a matrix:

     motors  age
[1,] "audi"  "1"
[2,] "honda" "2"
[3,] "ford"  "3"
[4,] "audi"  "2"
[5,] "honda" "3"
[6,] "ford"  "1"

Which is usually fine for me, but if I ever do need different data types (character, numeric), I use data.table::rbindlist():

data.table::rbindlist(list(dat1, dat2))

   motors age
1:   audi   1
2:  honda   2
3:   ford   3
4:   audi   2
5:  honda   3
6:   ford   1
jpsmith
  • 11,023
  • 5
  • 15
  • 36