Home > Back-end >  How to instantly append named values to a data frame based on it's corresponding name?
How to instantly append named values to a data frame based on it's corresponding name?

Time:01-25

I have a dataframe that has 6 columns

col1|col2|col3|col4|col5|col6
   1    3    4 r1   r2   5
   5    3    2 s1   s2   5   
   5    4    2 x1   s2   5 

Then I have 6 values

col1<-4
col2<-2
col3<-1
col4<-"f1"  
col5<-"s1"
col6<-7

How do I append those values into the dataframe based on its corresponding name so that I have

col1|col2|col3|col4|col5|col6
   1    3    4 r1   r2   5
   5    3    2 s1   s2   5   
   5    4    2 x1   s2   5 
   4    2    1 f1   s1   7

CodePudding user response:

If you're sure your environment only contains variables you want, you can use ls with as.name

col1<-4
col2<-2
col3<-1
col4<-"f1"  
col5<-"s1"
col6<-7

rbind(dat, data.frame(sapply(ls(pattern="col[1-6]"), as.name)))
  col1 col2 col3 col4 col5 col6
1    1    3    4   r1   r2    5
2    5    3    2   s1   s2    5
3    5    4    2   x1   s2    5
4    4    2    1   f1   s1    7

Data

dat <- structure(list(col1 = c(1L, 5L, 5L), col2 = c(3L, 3L, 4L), col3 = c(4L, 
2L, 2L), col4 = c("r1", "s1", "x1"), col5 = c("r2", "s2", "s2"
), col6 = c(5L, 5L, 5L)), class = "data.frame", row.names = c(NA, 
-3L))
  • Related