Nlopez
Nlopez

Reputation: 35

How to access variable names that are made from values in a data frame in R?

So I am importing a data frame, reorganizing the data frame based on the alphabetical order of names in a column, deleting duplicates of names and returns a vector of all players. I then create a data frame for every player using the vector of players with the corresponding columns that I want. The problem is that I want to access the new data frames of all players without having to individually call the new data frame names. Here's my code so far:

#Reorder entire data frame by alphabetical order in lastName column
entryDataFrame <- entryDataFrame[order(entryDataFrame$lastName),]

#Delete duplicates of Last Names and returns a vector of all players
playerNames <- unique(entryDataFrame$lastName)

#Create a dataframe for every player and assign GameID, lastName, keyValue, and Type.of.Entry
  for(i in 1:length(playerNames)){
      assign(paste(playerNames[i]), entryDataFrame[entryDataFrame$lastName %in% playerNames[i],])
      entryDataFrame$Minutes <- NULL
      entryDataFrame$Seconds <- NULL
      entryDataFrame$Period <- NULL
      entryDataFrame$Jersey <- NULL
      entryDataFrame$Team <- NULL
      entryDataFrame$Even <- NULL
      entryDataFrame$Odd <- NULL

Upvotes: 0

Views: 435

Answers (1)

Paul
Paul

Reputation: 2977

You can use the split() function to create a list in which each element is a dataframe containing the data for one player. Then, if you want to manipulate all the dataframes you just need to call the list.

Furthermore, you can use the functions from the apply family (apply(), lapply(), etc.) to apply a function to each element of the list. Here is a reproductible example :

    library("tidyverse")
# create a dummy table
test = data.frame(name = c("a", "a", "b", "b", "c"))
test = test %>% mutate(perf = c(3, 4, 2, 6, 8))
# create an object containing a dataframe per factor level of "name"
test_list = split(test, test$name)

If you want more precise help please provide a reproducible example.

Upvotes: 1

Related Questions