Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process vector nested within a nested list in R

Tags:

list

r

vector

I have a list of lists of vectors like the following:

myList = list(id1 = list(a=6:10,b=1:5),
              id2 = list(a=3:8,b = 4:9))

I would like to process the second vector named 'b' in each list with an arbitrary function (e.g., mean, sum, etc.) and append the result to a third named vector within each nested list to achieved something like:

myList2 = list(id1 = list(a=6:10,b=1:5,c = mean(1:5)),
          id2 = list(a=3:8,b = 4:9,c = mean(4:9)))

Thus, my question has two parts. First, how can I process only the second named vector in each nested list? Second, how can I append the result to each nested list?

I know I can write a for loop that always indexes myList[[i]][[2]], but I am looking for a vectorized solution. I've tried using various combinations apply-family with an anonymous function that first tests the name of the vector, for example:

rapply(myList, function(x) ifelse(names(x) == "b",
                              print("yes"),  #process vector
                              print("no")),  #move on to next x
   how = "list"
)

but the result doesn't make much sense.

Additional information: I'm using nested lists instead of a data.frame because I don't have the same number of observations for each id, but I am open to alternative approaches that might bypass these issues and accommodate different numbers of observations.

like image 707
John Jones Avatar asked Apr 21 '26 05:04

John Jones


1 Answers

This should do it

lapply(myList, function(x) {
  x$c <- mean(x$b)
  return(x)
})
like image 81
dimitris_ps Avatar answered Apr 23 '26 21:04

dimitris_ps