Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Frame alternately row binding in R

Tags:

r

rbind

I have two Data Frames which have the exact the same columns and the same numer of rows.

I want to create a new Data Frame which contains both data frames but having rows binded alternately. It has to take one row from first Data Frame and one row from the second Data Frame untill the whole new Data Frame is built.

I tried to use rbind() without luck. I need a solution that doesn't include installing new R packages.

Picture for demonstration:

DataFrame row binding

EDIT: My number of rows are dynamic and can be very large. Furthermore, I need a solution that doesn't rely on column names since the strucutre is dynamic as well. I know the two data frames have the same structure each time.

like image 373
DifferentPulses Avatar asked Jun 19 '26 17:06

DifferentPulses


1 Answers

You can use mapply with rbind, i.e.

d2 <- data.frame(a = c(4, 6, 8), b = c(letters[5:7]), stringsAsFactors = FALSE)
d1 <- data.frame(a = c(1, 2, 3), b = c(letters[1:3]), stringsAsFactors = FALSE)

mapply(rbind, d1, d2)
#      a   b  
#[1,] "1" "a"
#[2,] "4" "e"
#[3,] "2" "b"
#[4,] "6" "f"
#[5,] "3" "c"
#[6,] "8" "g"
like image 96
Sotos Avatar answered Jun 21 '26 09:06

Sotos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!