1

I have a bunch of individual dataframes that have names like day01_01_1of2, day01_01_2of2, day01_02_1of2, etc.

And I want to create a conditional statement that will find data-frames with the first characters matching (ie. day01_01) and bind the rows together. I cannot find any way to do this.

I can manipulate the data from a list in R: Image of the lists from Rstudio

or from individual data frames in the global environment

ls()
 [1] "day01_01_1of2" "day01_01_2of2" "day01_02_1of2" "day01_02_2of2" "day01_03_1of2"
 [6] "day01_03_2of2" "day01_04_1of2" "day01_04_2of2" "day01_05_1of2" "day01_05_2of2"
[11] "day01_06_1of2" "day01_06_2of2" "day01_07_1of2" "day01_07_2of2" "day01_08_1of2"
[16] "day01_08_2of2" "day01_09_1of2" "day01_09_2of2" "day01_10_1of2" "day01_10_2of2"

I am looking for any solutions whether they be in the list or outside of the list.

Thank you for any help you can give.

oguz ismail
  • 1
  • 16
  • 47
  • 69
K8Otter
  • 95
  • 7
  • [Don't ever create d1, d2, d3, ..., dn in the first place. Create a list d with n elements.](https://stackoverflow.com/a/24376207/1422451) – Parfait Mar 06 '20 at 00:25
  • Good. Keep as a *single* list rather than *many* objects. And since they are named elements, simply use the extract method `[`: `mylistofdfs[grep("day01_01", names(mylistofdfs))]`. Then `rbind`, `cbind`, or `merge` on subsetted list. No need to traverse global environment with `ls`, `get`, or `mget`. – Parfait Mar 06 '20 at 01:23

1 Answers1

1

We can do a split of the vector with substring of vector

str1 <- ls()
lst1 <- split(str1, sub("_[^_]+$", "", str1))
lst2 <- lapply(lst1, function(x) do.call(rbind, mget(x, inherits = TRUE)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you akrun. I am getting an error: Error: value for ‘day01_01_1of2’ not found 6. stop(gettextf("value for %s not found", sQuote(x)), call. = FALSE) 5. (function (x) stop(gettextf("value for %s not found", sQuote(x)), call. = FALSE))("day01_01_1of2") 4. mget(x) 3. do.call(rbind, mget(x)) 2. FUN(X[[i]], ...) 1. lapply(lst1, function(x) do.call(rbind, mget(x))) – K8Otter Mar 06 '20 at 00:06
  • Is there a way to do this same thing with all the data frames in a list (ie. str1 would actually be a list of all the data frames)? – K8Otter Feb 10 '21 at 19:59
  • @K8Otter `ls()` returns all the objects created in the global env. If you have only created data.frame, then the `mget` will get the value of those in a `list`. I didn't understand your question proprely – akrun Feb 10 '21 at 20:01
  • Essentially, can the third line be adapted such that it is using rbind on dataframes in a list rather than in the global env – K8Otter Feb 10 '21 at 20:24
  • May be you want `lapply(lst1, function(sublst) do.call(rbind, sublst))` – akrun Feb 10 '21 at 20:49