1

假设我有一个清单:

thelist=list(first=data.frame(Year=1:10,Time=rnorm(10)),second=data.frame(Year=1:10,Time=rnorm(10)),third=data.frame(Year=1:10,Time=rnorm(10)))

然后,我想为每个列表元素添加一列,该列的名称不同。

Test=mapply(function(x,y) {

     x$y=x$Time+0.5

     x=x[complete.cases(x[,3]),][,c(1,3)]      
                           }, 
     x=thelist,y=c("Add1","Add2","Add3") 

        )

答案是

Test
     first      second     third     
Year Integer,10 Integer,10 Integer,10
y    Numeric,10 Numeric,10 Numeric,10

这不是我所期望的。我希望答案是:

Test[1:2]

$first
   Year  Time  Add1 
1     1 -0.27  Some values...
2     2  0.76
3     3  1.53
4     4  1.00
5     5 -0.25
6     6  0.64
7     7 -0.38
8     8  1.52
9     9 -1.18
10   10 -0.97

$second
   Year   Time  Add2
1     1  0.330  Some values...
2     2  0.075
3     3  1.357
4     4 -1.393
5     5 -0.382
6     6 -0.016
7     7  0.604
8     8 -0.721
9     9  0.665
10   10 -1.115

Update

如果我使用SIMPLIFY=FALSE

Test=mapply(function(x,y) {

  x$y=x$Time+0.5

  x=x[complete.cases(x[,3]),][,c(1,3)]      
}, 
            x=thelist,y=c("Add1","Add2","Add3"),SIMPLIFY=FALSE 

)

Test[1:2]
$first
   Year     y
1     1  0.23
2     2  1.26
3     3  2.03
4     4  1.50
5     5  0.25
6     6  1.14
7     7  0.12
8     8  2.02
9     9 -0.68
10   10 -0.47

$second
   Year     y
1     1  0.83
2     2  0.57
3     3  1.86
4     4 -0.89
5     5  0.12
6     6  0.48
7     7  1.10
8     8 -0.22
9     9  1.16
10   10 -0.62
4

3 回答 3

0

使用SIMPLIFY = FALSE或替换mapplyMap.

于 2013-09-04T12:09:50.067 回答
0

尝试这个:

Test <- mapply(function(x,y) {
    x[[y]] <- x$Time + 0.5
    x <- x[complete.cases(x[,3]), c(1,3)]  
  }, 
  thelist, c("Add1","Add2","Add3"), SIMPLIFY = FALSE)
于 2013-09-04T12:21:51.870 回答
0

使用lapply

lapply(seq(thelist), function(i) within(thelist[[i]][complete.cases(thelist[[i]]$Time),], assign(y[i],Time+0.5)))
于 2013-09-04T12:27:08.503 回答