paul kraus
paul kraus

Reputation: 1

How to dynamically create and name data frames in a for loop

I am trying to generate data frame subsets for each respondent in a data frame using a for loop. I have a large data frame with columns titled "StandardCorrect", "NameProper", "StartTime", "EndTime", "AScore", and "StandardScore" and several thousand rows. I want to make a subset data frame for each person's name so I can generate statistics for each respondent. I tried using a for loop

for(name in 1:length(NamesList)){ name <- DigiNONA[DigiNONA$NameProper == NamesList[name], ] }

NamesList is just a list containing all the levels of NamesProper (which isa factor variable)

All I want the loop to do is each iteration, generate a new data frame with the name "NamesList[name]" and I want that data frame to contain a subset of the main data frame where NameProper corresponds to the name in the list for that iteration.

This seems like it should be simple I just can;t figure out how to get r to dynamically generate data frames with different names for each iteration.

Any advice would be appreciated, thank you.

Upvotes: 0

Views: 670

Answers (1)

IRTFM
IRTFM

Reputation: 263301

The advice to use assign for this purpose is technically feasible, but incorrect in the sense that it is widely deprecated by experienced users of R. Instead what should be done is to create a single list with named elements each of which contains the data from a single individual. That way you don't need to keep a separate data object with the names of the resulting objects for later access.

named_Dlist <- setNames( split( DigiNONA, DigiNONA$NameProper),
                         NamesList)

This would allow you to access individual dataframes within the named_Dlist object:

named_Dlist[[ NamesList[1] ]] # The dataframe with the first person in that NamesList vector. 

It's probably better to use the term list only for true R lists and not for atomic character vectors.

Upvotes: 2

Related Questions