2
votes

I have several dataframes of different length and I am trying to add a variable to each of them containing a constant taken from a list, where each dataframe is assigned a different entry from that list.

How can automate this using a loop or lapply? My pathetic attempt below obviously doesn't give the desired result, as it pastes all entries from the list:

A = data.frame( v=c('x','x','y','y','z','z') )
B = data.frame( v=c('x','y','z') )
C = data.frame( v=c('x','x','x','y','y','y','z','z','z') )

Mylist = list('a','b','c')

# desired result:
A$new <- Mylist[1]
B$new <- Mylist[2]
C$new <- Mylist[3]

# failed attempt to use lapply:
dfs <- lapply(list(A, B, C), function(d) {
       d$new1 <- Mylist
       d
       })

This is the output I get:

> dfs
[[1]]
  v new new1
1 x   a    a
2 x   a    b
3 y   a    c
4 y   a    a
5 z   a    b
6 z   a    c

[[2]]
  v new new1
1 x   b    a
2 y   b    b
3 z   b    c

 [[3]]
   v new new1
 1 x   c    a
 2 x   c    b
 3 x   c    c
 4 y   c    a
 5 y   c    b
 6 y   c    c
 7 z   c    a
 8 z   c    b
 9 z   c    c

Any help would be very much appreciated.

1
could you please provide a sample output? - akash87
is that the output you want or you get? - akash87
The variable "new" is what I want to get (and achieve, if I do it manually), the variable "new1" is the result of my failed attempt to automate it using lapply. - Luise

1 Answers

2
votes

Check if this works:

df_list <- list(A, B, C)

dfs <- lapply(seq_along(df_list), function(i) {
  df_list[[i]] <- cbind(df_list[[i]], Mylist[[i]])
})