I do have some grasp on how to use lapply to, say, change the names of variables in several dataframes in a list. However, I am looking to carry out a slightly (but only slightly) more complicated operation.
More specifically, I am looking to calculate the mean growth rates for several entities. The growth rate have already been calculated, so I just need to perfor the following operations on all dataframes
for (i in 1:13) {
growth.type[,i] <- tapply(growth[,8+i] , growth$type, mean, na.rm = TRUE)
}
This creates a new dataframe ( growth.type
) that includes the mean of all several hundred growth rates in the original dataframe ( growth
), by type
.
Now, I would like to do this to several dataframes (like growth
) and put them into new dataframes (like growth.type
).
I hope this makes sense.
Put all data.frames you wish to process in a list
xy <- list(growth1, growth2, growth3, ...)
and then apply a custom function to this xy
object.
customFunction <- function(.data) {
for (i in 1:13) {
growth.type[,i] <- tapply(.data[,8+i] , .data$type, mean, na.rm = TRUE)
}
growth.type # this is the object which will be returned when function finishes
}
then just do
out <- lapply(xy, FUN = customFunction)
If you want to combine the result of lapply
, you can use do.call
, eg do.call("rbind", out)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.