I'm trying to embrace the apply family more, but still having trouble. I mostly understand simple cases with lapply (as below), but am having issues with more complicated apply functions.
I have a for loop function that iterates through a nested list and adds a new subset list. How could I write this using the apply family of functions?
mylist <- list(mtcars=mtcars, iris=iris)
mylist <- lapply(mylist,
function(sub) list(data=sub))
for (i in head(seq_along(mylist))){
mylist[[i]]$new <- mylist[[i]]$data[,c(1,4,5)]
}
Which gives:
> mylist$mtcars$new
mpg hp drat
Mazda RX4 21.0 110 3.90
Mazda RX4 Wag 21.0 110 3.90
Datsun 710 22.8 93 3.85
Hornet 4 Drive 21.4 110 3.08
> mylist$iris$new
Sepal.Length Petal.Width Species
1 5.1 0.2 setosa
2 4.9 0.2 setosa
3 4.7 0.2 setosa
4 4.6 0.2 setosa
lapply(mylist, function(lst) { lst$new <- lst$data[c(1,4,5)]; lst;})? - r2evansapplyis used for objects with dimensions. - IRTFMlstfromdplyror just a variable name? Function of;? Really trying to make sure I understand...thanks - moxedlsthere is just a temporary variable named in the anonymous function, alafunction(lst) {...}. It could have beenaorsome_other_variable_name, as long as the inner code reference that name instead oflst. As for the semi-colon: typically lines of code in R are terminated or separated with a newline, but a semi-colon can be used as well. I really only use semi-colons here on SO in comments, otherwise I tend to use multi-line calls. - r2evanslst. You need the whole (updated) object returned, so you need to be explicit. - r2evans