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.
This should do it
lapply(myList, function(x) {
x$c <- mean(x$b)
return(x)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With