0

Very easy question but I cannot find a solution.

I have a list of data frames (part1,part2,part3)

dfList = list(part1,part2,part3)

And I would like to calculate for each of the data frames new columns.

part1$sum
part1$rest

So I don't want to write the code for each single data frames in the list and, since the new columns are identicals for all data frames, I was thinking to use a loop, so I can write the code for one operation and that's it!

How can I do it?

Thank you! :)

Jordan
  • 35
  • 5
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. How exactly do you want to calculate `sum` and `rest` and where to you want these values to go exactly? – MrFlick Jan 02 '19 at 19:53
  • Possible duplicates: https://stackoverflow.com/questions/19460120/looping-through-list-of-data-frames-in-r, https://stackoverflow.com/questions/32007076/loop-through-list-of-data-frames – MrFlick Jan 02 '19 at 20:10
  • 1
    This is a common use case in R. Did you make any attempt at the solution? Please post and describe errors or undesired results. – Parfait Jan 02 '19 at 20:10
  • `lapply(dfList, function(DF){DF$sum <- code; DF})`. Do not forget to return the data.frame `DF` in the end. – Rui Barradas Jan 02 '19 at 20:33
  • 1
    @RuiBarradas ... or use `within` to avoid return line: `lapply(dfList, function(DF) within(DF, {sum <- code; rest <- code}))`. – Parfait Jan 02 '19 at 20:52

0 Answers0