jrara
jrara

Reputation: 16981

How to append a vector to a list of data.frames?

How can I cbind/append a vector to a list of data.frames?

l <- list(data.frame(a=c(1,2,3), b=c(1,2,3)), data.frame(a=c(1,2,3,4), b=c(1,2,3,4)))
l
file_name <- c("myfile.txt", "yourfile.txt")
file_name

I tried:

lapply(l, function(x) cbind(l[[x]], fname = rep(file_name, each = nrow(l[[x]]))))

but I get an error:

Error in l[[x]] : invalid subscript type 'list'

Upvotes: 1

Views: 166

Answers (2)

zwep
zwep

Reputation: 1340

Just to make sure.. you have the following list of data.frames..

l <- list(data.frame(a=c(1,2,3), b=c(1,2,3)), data.frame(a=c(1,2,3,4), b=c(1,2,3,4)))
l
[[1]]
  a b
1 1 1
2 2 2
3 3 3

[[2]]
  a b
1 1 1
2 2 2
3 3 3
4 4 4

Where you eventually want to cbind a vector (which differ per list) to all data.frames in the list.. so you want to have

[[1]]
  a b v
1 1 1 a
2 2 2 b
3 3 3 c

[[2]]
  a b v
1 1 1 a
2 2 2 b 
3 3 3 c
4 4 4 d

One trick that we can do is to first use rbindlist to get all of the frames together.. and keep their id's

L = rbindlist(l,idcol = TRUE)

And let's say that we also have a list that we wanted to append to each data.frame

v = list(data.frame(v = letters[1:3]), data.frame(v = LETTERS[1:4]))
V = rbindlist(v)

Now we can do a simple cbind and then split the list using the .id that we created

result = cbind(L,V)
final_result = split(result,on = ".id")

    $`1`
   .id a b v
1:   1 1 1 a
2:   1 2 2 b
3:   1 3 3 c

$`2`
   .id a b v
1:   2 1 1 A
2:   2 2 2 B
3:   2 3 3 C
4:   2 4 4 D

We still have an .id column there.. but that shouldnt be too much trouble to get rid of that one..

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use Map to create a new column 'fname' for each of thelist` elements by appending the corresponding 'file_name' to it

Map(cbind, l, fname = file_name)

If we are using lapply, then loop through the sequence of the list

lapply(seq_along(l), function(i) transform(l[[i]], fname = file_name[i]))

Upvotes: 1

Related Questions