Home > Enterprise >  rbind/bind_rows two unequal data.frames
rbind/bind_rows two unequal data.frames

Time:01-21

Below, I wonder how to rbind dat2 to dat1 such that I can achieve my Desired_output below?

Note that no new columns has to be added. (see the desired output)

fit <- lm(mpg ~ hp, data = mtcars)

dat1 <- as.data.frame(coef(summary(fit)))

dat2 <- data.frame(Estimate = 2, pr = 0.1234567901, row.names = "Q")

Desired_output =
"
               Estimate Std. Error   t value     Pr(>|t|)
(Intercept) 30.09886054  1.6339210 18.421246 6.642736e-18
hp          -0.06822828  0.0101193 -6.742389 1.787835e-07
Q            2.00000000         NA        NA 0.1234567901
"

CodePudding user response:

A possible solution, which requires names(dat2)[2] <- names(dat1)[4] before binding the rows (there was a mismatch of column names):

library(tidyverse)

fit <- lm(mpg ~ hp, data = mtcars)

dat1 <- as.data.frame(coef(summary(fit)))

dat2 <- data.frame(Estimate = 2, pr = 0.1234567901, row.names = "Q")

names(dat2)[2] <- names(dat1)[4] # <--- This is CRUCIAL

dat1 %>% 
  bind_rows(dat2)

#>                Estimate Std. Error   t value     Pr(>|t|)
#> (Intercept) 30.09886054  1.6339210 18.421246 6.642736e-18
#> hp          -0.06822828  0.0101193 -6.742389 1.787835e-07
#> Q            2.00000000         NA        NA 1.234568e-01

CodePudding user response:

In base R:

rbind(dat1, Q = list(dat2[1], NA, NA, dat2[2]))

               Estimate Std. Error   t value     Pr(>|t|)
(Intercept)    30.09886  1.6339210 18.421246 6.642736e-18
hp          -0.06822828  0.0101193 -6.742389 1.787835e-07
Q                     2         NA        NA    0.1234568
  •  Tags:  
  • Related