user2165379
user2165379

Reputation: 479

How to efficiently append values to a dataframe and give a column name?

I have a row of data (my_row) for which I would like to add new column and fill this column with a number from a specific position in another dataframe (df). At the same time I would like to give this column a name ("m5").

Please find, below, my data:

my_row <- data.frame(m1 = c(1), 
                     m2 = c(4), 
                     m3 = c(3), 
                     m4 = c(3))
  
  
df <- data.frame(x1 = c(1,2,3), 
                 x2 = c(4,1,6), 
                 x3 = c(3,0,2), 
                 x4 = c(3,0,1))

I can reach my goal with the code below, although this looks quite cumbersome to me. Is there a more elegant way to do this?

library(dplyr)
  
my_number <- as.data.frame(df$x2[2])
colnames(my_number)[1] <- "m5"
my_row <- dplyr::bind_cols(my_row, my_number)


my_row
   m1 m2 m3 m4 m5
1  1  4  3  3  1

Upvotes: 0

Views: 234

Answers (3)

akrun
akrun

Reputation: 886938

Or just cbind in base R, if we don't want to to update the original object

cbind(my_row, m5 = df$x2[2])
  m1 m2 m3 m4 m5
1  1  4  3  3  1

Upvotes: 1

TarJae
TarJae

Reputation: 78917

Base R:

my_row$m5 <- df$x2[2]
my_row
  m1 m2 m3 m4 m5
1  1  4  3  3  1

Upvotes: 3

benson23
benson23

Reputation: 19097

What you need is mutate().

library(dplyr)

my_row %>% mutate(m5 = df$x2[2])

 m1 m2 m3 m4 m5
1  1  4  3  3  1

Upvotes: 1

Related Questions