regents
regents

Reputation: 626

create many subsets at once

I have a large dataset based on some medical records so I cannot post a sample due to privacy restrictions, but I am trying to subset the one data frame into many. The goal is for each unique facility to be its own data frame so I can identify efficiency rates for each facility. I have tried the following code where df is the name of the data frame, Name is the name I will give to the subset, Location is the value of interest from the variable "Facility" from the original dataframe:

ratefunct <- function(df, Name, Facility) {Name <- subset(df, Facility, == "Location")
Name <- within(Name, {rate <- <-cumsum(Complete)/ cumsum(Complete+Incomplete) })}

but don't seem to be getting any results in my environment

Upvotes: 0

Views: 121

Answers (1)

Mako212
Mako212

Reputation: 7312

Based on your comment, it sounds like you're trying to store the results of split as separate data frames.

You can do so like this, using assign

dfL <- split(iris, iris$Species)

for (i in 1:length(dfL)){
  assign(paste0("df_", names(dfL[i])), dfL[i])

# added the print line so you can see the names of the objects that are created

  print(paste0("df_",names(dfL[i])))

}

[1] "df_setosa"
[1] "df_versicolor"
[1] "df_virginica"

Which will create data frames df_setosa, df_virginica, and df_versicolor


Alternatively, if you're happy with the current object names, you could simply use:

list2env(dfL,envir=.GlobalEnv)

Which will save each list item as an object, using the object's name in the list. So instead of having the df_ prefix, you would just have setosa, virginica, and versicolor objects.


Edit: as a simpler way to assign custom names to each created object, directly specifying the names of dfL is a nice clean solution:

names(dfL) <- paste0("df_",names(dfL))
list2env(dfL,envir=.GlobalEnv)

This way you avoid having to write the for loop, and still get object names with a useful prefix.

Upvotes: 3

Related Questions