Home > Back-end >  Adding a vector to a data.frame in an asymmetric way in R
Adding a vector to a data.frame in an asymmetric way in R

Time:12-24

In my code below, I was wondering if there might be a way to add the z1 vector to data.frame d1 such that we can achieve my Desired_Output using Base R or tidyverse?

This is a toy example. Thus, d1 can have any number of rows and columns and z1 vector can have any number elements. Thus, a functional answer applicable to other data.frames is highly appreciated.

d1 <- data.frame(b = 1:5, SE = 2:6)
z1 <- c(2.3, 5.4)
d1$tau <- ""

Desired_Output =
 " b SE tau
   1  2    
   2  3    
   3  4    
   4  5    
   5  6
       2.3
       5.4"

CodePudding user response:

You may use dplyr::bind_rows or data.table::rbindlist

d1 <- data.frame(b = 1:5, SE = 2:6)
z1 <- c(2.3, 5.4)
d2 <- data.frame(tau = z1)
dplyr::bind_rows(d1, d2)

#   b SE tau
#1  1  2  NA
#2  2  3  NA
#3  3  4  NA
#4  4  5  NA
#5  5  6  NA
#6 NA NA 2.3
#7 NA NA 5.4

With data.table -

data.table::rbindlist(list(d1, d2), fill = TRUE)

CodePudding user response:

The d1 data frame has 5 rows and two columns. To add a column, it, too, must have 5 rows. However, because it is required for the z vector to occupy rows 6 and 7, those rows must first be added to d1:

d1 <- data.frame(b = 1:5, SE = 2:6)
d1[6:7,] <- NA
d1$tau <- c(rep(NA,5),2.3,5.4)
d1
#>    b SE tau
#> 1  1  2  NA
#> 2  2  3  NA
#> 3  3  4  NA
#> 4  4  5  NA
#> 5  5  6  NA
#> 6 NA NA 2.3
#> 7 NA NA 5.4
  • Related