I would like to create a loop over 3 data frames and creates subsets of each and assign to these new subsets a new name. How can I loop over these three data frames while maintaining the names?
For example, I have 3 data frames: apples, berries, and grapes. When making a loop, is there a way to assign the new subset data frames similar names to their respective original data frame?
Written out without a loop, this is what the code would look like.
apples <- data.frame(type = c("red", "golden", "green"), number = c(1, 2, 3))
berries <- data.frame(type = c("blueberry", "raspberry", "mulberry"), number = c(1, 2, 3))
grapes <- data.frame(type = c("red", "green", "sour"), number = c(1, 2, 3))
apples_large <- subset(apples, number > 2)
apples_small <- subset(apples, number < 2)
berries_large <- subset(berries, number > 2)
berries_small <- subset(berries, number < 2)
grapes_large <- subset(grapes, number > 2)
grapes_small <- subset(grapes, number < 2)
Place the dataset objects in a list
and split
by the 'number' column to get a nested list
of datasets
lapply(list(apples, berries, grapes), function(x) split(x, x$number>2))
If we create a named list
, then it becomes easier to identify or extract the individual components
out <- lapply(mget(c("apples", "berries", "grapes")),
function(x) split(x, c("small", "large")[(x$number > 2) + 1]))
out$apples$small
As @JonMinton mentioned if we need to drop the rows that have 'number' 2
lapply(mget(c("apples", "berries", "grapes")),
function(x) {x1 <- subset(x, number != 2)
split(x1, c("small", "large")[(x1$number > 2) + 1])})
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