1

I have multiple data frames and need calculate mean and SE per week for each dataframe, and save as csv.

In this case, I know the "for loop" is working because I always get the tempdf for df3. I am having difficulty creating and naming a separate csv for each df (e.g. Curated_df1.csv, Curated_df2.csv, Curated_df3.csv).

library(plyr)
list = list (df1, df2, df3)

for (x in list){

    tempdf = ddply (x, c("week"),
       N = lenght (variable),
       mean = mean (variable),
       SD = sd (variable),
       SE = sd/ sqrt(N))

    tempname = paste ("Curated_", x, ".csv", sep = "")
    write.csv (tempdf, tempname, na="")

    }
smci
  • 32,567
  • 20
  • 113
  • 146
CAA
  • 79
  • 6
  • `for (x in 1:list){` – Chabo Oct 16 '18 at 19:08
  • 3
    @Chabo `list` is a list in this example. You can't do `1:list(1,2,3)`. Maybe you wanted something like `for (i in seq_along(list))`? – MrFlick Oct 16 '18 at 19:13
  • 3
    Possible duplicate: https://stackoverflow.com/questions/4209512/write-list-of-data-frames-to-separate-csv-files-with-lapply – MrFlick Oct 16 '18 at 19:14
  • @MrFlick Good heads up – Chabo Oct 16 '18 at 19:18
  • `list(df1, df2, df3)` is an actual list of dataframes, not string names of dataframes. You want to reference variables by their (string) names. See [Access variable value where the name of variable is stored in a string in R](https://stackoverflow.com/questions/3971844/access-variable-value-where-the-name-of-variable-is-stored-in-a-string-in-r). **Anyway your answer is the bizarrely-named [`get()`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html)** – smci Oct 17 '18 at 00:57
  • Esssentially a duplicate of [Access variable value where the name of variable is stored in a string in R](https://stackoverflow.com/questions/3971844/access-variable-value-where-the-name-of-variable-is-stored-in-a-string-in-r) – smci Oct 17 '18 at 00:57

1 Answers1

1

When you do paste ("Curated_", x, ".csv", sep = ""), it doesn't work because x is a data.frame, and not a character object. If you have a list where each element has a name, you can use iwalk from purrr and use .y to refer to the list element's name, and .x to refer to the list element. Below I create a list where each element is named and use iwalk.

library(plyr)
my_list = list(name1 = df1, 
               name2 = df2, 
               name3 = df3)

library(purrr)

iwalk(my_list, ~{
    tempdf = ddply (.x, c("week"),
     N = lenght (variable),
     mean = mean (variable),
     SD = sd (variable),
     SE = sd/ sqrt(N))

    tempname = paste ("Curated_", .y, ".csv", sep = "")
    write.csv (tempdf, tempname, na="")
})
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38