oercim
oercim

Reputation: 1848

Getting error using cbind in lapply-R

Let I have a list of data frames(l1) and I have a vector (v1) which consists integers.

I want to combine v1 with each elements of l1. Let:

l1[[1]]:

head1
-----
4
3.2
4.1

l1[[2]]:

head2
-----
1.2
0.9
3.2 

and let

v1:

head3
-----
5
4
7

So the resulting list(l2) should be:

l2[[1]]:

   head3 head1
   ----- -----
    5    4
    4    3.2
    7    4.1

l2[[2]]:

   head3 head2
   ----- -----
    5    1.2
    4    0.9
    7    3.2 

I use the below code:

l2<-lapply(l1, function(i) cbind(v1,l1[[i]]))

However, I get such an error:

Error in lapply(l1, function(i) cbind(z, l1[[i]])) : 
  object 'l1' not found

Why do I get this error? I will be very glad for any help. Thanks a lot.

Upvotes: 3

Views: 1792

Answers (1)

akrun
akrun

Reputation: 887048

We can use Map

Map(cbind, l1, v1)

In case 'v1' is a vector

Map(cbind, l1, list(v1))

Or just loop through the sequence of 'l1' with lapply

lapply(seq_along(l1), function(i) cbind(v1, l1[[i]]))

Or use transform to create a new column

lapply(l1, transform, head3=v1$head3)

NOTE: Assuming that 'v1' is a data.frame


The error in OP's code occurred because it is looping through 'l1'. Each element of 'l1' is a 'data.frame'. So, we can use that for subsetting. Either, we should loop through the sequence of 'l1' and subset the 'l1' by indexing or pass the 'l1' directly and create the column.

Upvotes: 3

Related Questions