-1

I have seen similar posts but no one that address specifically this question. I have 22 data frames called chr1,chr2,chr3,...,chr22. I want to apply a home-made function "diff_set" to all these data frames and generate 22 new data frames with names chr1.1,chr2.1,chr3.1,...,chr22.1. The function is applied to one of the columns. For instance, for chr1, I apply diff_set and generate chr1.1:

chr1.1 = diff_set(chr1$POSITION, 200000)

Any suggestion is welcome !

Lucas
  • 1,139
  • 3
  • 11
  • 23
  • I'm not aware of a way to do so much assignment easily. You could use the `apply` family or `purrr::map` to apply the function to a list of your dataframes, returning a list of dataframes; but it won't store each dataframe individually – zlipp Oct 26 '17 at 14:54
  • 1
    I urge you to deal with a [`list` of data.frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) instead of individual data.frames. If you have all `chr1`, etc stored within a single list-of-frames names `chrs`, then the answer to this question might be simply `newchrs <- lapply(chrs, diff_set, 200000)`. – r2evans Oct 26 '17 at 15:25

1 Answers1

2

Simply lapply a list of dataframes on your function, diff_set, rename your output list and then if really needed but should be avoided run list2env to save individual dfs as separate objects:

output_list <- lapply(mget(paste0("chr", seq(1,22))),
                      function(df) diff_set(df$POSITION, 20000))

output_list <- setNames(output_list, paste0("chr", seq(1,22)+0.1))

# FIRST THREE DFS
output_list$chr1.1
output_list$chr2.1
output_list$chr3.1

# OUTPUT EACH DF AS SEPARATE OBJECT
# (BUT CONSIDER AVOIDING THIS AS YOU FLOOD GLOBAL ENVIRONMENT)
list2env(output_list, envir=.GlobalEnv)
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • 1
    +1 to "consider avoiding this" ... several times I've found poorly-maintained code over-writing global vars in this fashion; that's a very difficult bug to track down! – r2evans Oct 26 '17 at 18:55
  • Hello @Parfait, when I do output_list$chr1.1 I get only a vector of the column where the function diff_set was computed, but not the rest of the columns in the data frame. Any suggestion? Thank you very much for your help – Lucas Jan 17 '18 at 12:02
  • Hmmm...I would check your `diff_set` function as it may not be returning a dataframe as your original post above claims. Always check the last line of your function or use `return(df)`. – Parfait Jan 17 '18 at 16:10