'How to replicate a function for a nested list
I have a nested list (datalist) which I'd like to repeat the following function for. Within datalist are multiple dataframes (e.g., A-F).
After doing the following for the nested dataframe "A", I'd like to run it for the other nested dataframes (B-F):
dat_A_dat<-datalist["A"]
dat_A <- dat_A_dat$"A"[,c(1:4,7)] #note: I have to use $ to access this
dat_A.v <-dat_A[,c(1,2)]
dat_A.b <-dat_A[,3]
dat_A.c <-dat_A[,4]
dat_A.r <-dat_A[,7]
Is there a simpler way of doing this?
Your help would be greatly appreciated. Thank you all.
Solution 1:[1]
Its not clear what structure your data is or what exactly you're trying to achieve, but if you're just asking how to write a function that can be applied to each element of the list then it would be something like as follows.
Note: you might have to change this depending on the structure of your data and what you are trying to achieve, in future try to include a reproducible example
my_extraction_function <- function(d_list) {
dat <- d_list$"A"[,c(1:4,7)] #note: I have to use $ to access this
dat.v <-dat[,c(1,2)]
dat.b <-dat[,3]
dat.c <-dat[,4]
dat.r <-dat[,7]
# Return them in whatever format you want
list(v = dat.v,
b = dat.b,
c = dat.c,
r = dat.r)
}
You can then do:
my_extraction_function(datalist[["A"]])
my_extraction_function(datalist[["B"]])
... etc.
or
lapply(datalist, my_extraction_function)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cnbrownlie |
