Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop keeping variable names R

Tags:

loops

r

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) 
like image 326
user10156381 Avatar asked Jan 27 '23 16:01

user10156381


1 Answers

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])})   
like image 55
akrun Avatar answered Feb 02 '23 16:02

akrun