0

I have many dataframes that I would like to run though a code. Is there a way to change the dataframe name in a loop?

df01$x = rnorm(100)
df02$x = rnorm(100)+2
df03$x = rnorm(100)*2

dflist <- c("df01", 
            "df02",
            "df03")
for (i in 1:length(dflist){
  {
    #complete tasks by changing df name in existing code
    ifelse([[i]]$x > 0,1,[[i]]$x)
}
#I want to do this for a  number of different fuctions, so it is best to change the df name before "$"
    df[[i]]$Varible = aggregate(df$Varible, .. ,..)}
user_n
  • 53
  • 7
  • 1
    You should put the data.frames into a list. See [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) on how to do that. Take a good read of gregors answer there as it gives a number of method for working with lists of data.frames. – lmo Jun 28 '16 at 20:46

1 Answers1

0

Consider interacting with collection of data frames in a list and not passing string literals of its names. Within an lapply() function, you can handle your operations, and then even convert each back into individual dataframe objects:

df01 <- data.frame(x=rnorm(100))
df02 <- data.frame(x=rnorm(100)+2)
df03 <- data.frame(x=rnorm(100)*2)

# LIST OF DATAFRAMES (NAMED WITH LITERALS)
dfList <- list(df01=df01, df02=df02, df03=df03)
head(dfList[[1]])
#            x
# 1  1.3440091
# 2  0.5838570
# 3 -0.2377477
# 4 -1.5059733
# 5 -1.0605490
# 6 -0.8122972

# ITERATIVELY RUN COLUMN OPERATION 
dfList <- lapply(dfList, function(df) {
  df$x <- ifelse(df$x > 0, 1, df$x)
  return(df)
})

# CONVERT LIST ITEMS INTO INDIVIDUAL ENVIRON OBJECTS
list2env(dfList, envir=.GlobalEnv)
head(df01)
#            x
# 1  1.0000000
# 2  1.0000000
# 3 -0.2377477
# 4 -1.5059733
# 5 -1.0605490
# 6 -0.8122972
Parfait
  • 87,576
  • 16
  • 87
  • 105