简体   繁体   English

在 lapply-R 中使用 cbind 出错

[英]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.让我有一个数据帧列表(l1),我有一个由整数组成的向量(v1)。

I want to combine v1 with each elements of l1.我想将 v1 与 l1 的每个元素结合起来。 Let:让:

l1[[1]]: l1[[1]]:

head1
-----
4
3.2
4.1

l1[[2]]: l1[[2]]:

head2
-----
1.2
0.9
3.2 

and let然后让

v1: v1:

head3
-----
5
4
7

So the resulting list(l2) should be:所以结果列表(l2)应该是:

l2[[1]]: l2[[1]]:

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

l2[[2]]: 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.非常感谢。

We can use Map我们可以使用Map

Map(cbind, l1, v1)

In case 'v1' is a vector如果 'v1' 是一个vector

Map(cbind, l1, list(v1))

Or just loop through the sequence of 'l1' with lapply或者只是用lapply循环遍历 'l1' 的序列

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

Or use transform to create a new column或者使用transform来创建一个新列

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

NOTE: Assuming that 'v1' is a data.frame注意:假设 'v1' 是一个data.frame


The error in OP's code occurred because it is looping through 'l1'.发生 OP 代码中的错误是因为它正在循环“l1”。 Each element of 'l1' is a 'data.frame'. 'l1' 的每个元素都是一个 '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.或者,我们应该遍历 'l1' 的序列并通过索引对 'l1' 进行子集化,或者直接传递 'l1' 并创建列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM