Question

Say I have a list:

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)))

I then want to add a column to each list element, where the names for that column differ.

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") 

        )

And the answer is

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

It is not what I expect. I would like the answer to be:

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:

If I use 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
Was it helpful?

Solution

try this:

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)

OTHER TIPS

Use SIMPLIFY = FALSE or replace mapply with Map.

Using lapply:

lapply(seq(thelist), function(i) within(thelist[[i]][complete.cases(thelist[[i]]$Time),], assign(y[i],Time+0.5)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top