Search code examples
rlistlapplysapply

Returns function results from list with different data structure. (using lapply or sapply function)


I'm struggling with list.

I have a list with different data structure as below

mylist<-list(dat1=c(rep(5:9, times=2)), dat2=seq(50,120,by=6), dat3=data.frame(a=c(1:4),b=c(-1:2)))

What I want to do is to apply a function to each element of mylist by using

lapply or sapply function. like lapply(mylist, function(x) mean(x) )

But here is my problem. dat3 in mylist is data frame and it has two variables, but lapply and sapply function like returns only one maximum and average values.

Outputs what I want to get are

 $dat1             
    max    mean 
     9       7
 $dat2
    max   mean
     116    83
 $dat3
      a              b
    max mean     max mean 
     4   2.5      2   0.5

Solution

  • Maybe something like this?

    lapply(mylist,function(x){
      lapply(data.frame(x),function(y){
        data.frame(max=max(y),mean=mean(y))
      })
    })
    
    $dat1
    $dat1$x
      max mean
    1   9    7
    
    
    $dat2
    $dat2$x
      max mean
    1 116   83
    
    
    $dat3
    $dat3$a
      max mean
    1   4  2.5
    
    $dat3$b
      max mean
    1   2  0.5