0

I want to access data frames in a loop(df_1,df_2,df_3,df_4).So I tried to use the following code

for(i in 1:4){
      total[i]=sum(paste0("df_",i)$percentage)

}

But it throws the error operator invalid for atomic vector.So how is it possible to read the data frames in a loop?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
RKR
  • 657
  • 3
  • 13
  • 26
  • 2
    Helpful link for you http://stackoverflow.com/questions/16714020/loop-through-data-frame-and-variable-names, http://stackoverflow.com/questions/17634076/how-can-r-loop-over-data-frames, and http://stackoverflow.com/questions/28802652/access-variable-dataframe-in-r-loop – Saurabh Chauhan Jan 27 '17 at 04:20
  • 1
    Well, this would have been easier had you not created a bunch of different variables in the first place. It sounds like all those data.frames should be in a list. How exactly did you go about creating them? – MrFlick Jan 27 '17 at 04:20

1 Answers1

1

What you probably are trying to do is,

listdf <- mget(paste0("df", 1:4))
sapply(listdf, function(x) sum(x["percentage"]))

accessing the object with name using mget and making a list of dataframes and then for each dataframe in the list finding the sum of the percentage column

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213