0

Suppose I have 3 dataframes in the current R environment, named as d1f, df2, df_3. There is no pattern for their names. How can I access one dataframe by its name?

For example, I have a for loop to process the three dataframes. How can I do something like this?

df_names<-c("d1f", "df2", "df_3")
for(name in df_names)
{
  df<-some_function(name)

  ....some action on df....
}
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
Ding Li
  • 515
  • 1
  • 4
  • 14
  • 1
  • 2
    But it would be better to store related data.frames in a list so you don't have to mess with `get()`. See: https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames – MrFlick Jun 23 '17 at 16:48
  • and for that matter, if you already know the names of your data frames, `mget` is a good way to pull them into a list (if scripting them into a list at their creation is not an option). – Benjamin Jun 23 '17 at 17:03

1 Answers1

0

Best is to store the data frames in a list like so:

set.seed(1)

d1f = rnorm(10)
df2 = rnorm(10)
df_3 = rnorm(10)

dfs = list(d1f, df2, df_3)

for (i in 1:length(dfs)){
    dfs[[i]] = dfs[[i]] +1   # eg. add 1 to each element of the three data frames
}
user 123342
  • 423
  • 8
  • 20