Search code examples
rdataframenamesrbind

How do I merge data frames with matching characters in the object name?


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.


Solution

  • 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)))