【问题标题】:How do I merge data frames with matching characters in the object name?如何合并具有对象名称中匹配字符的数据框?
【发布时间】:2020-03-05 22:19:08
【问题描述】:

我有一堆单独的数据框,它们的名称如day01_01_1of2、day01_01_2of2、day01_02_1of2 等。

我想创建一个条件语句,它会找到第一个字符匹配的数据帧(即day01_01)并将行绑定在一起。我找不到任何方法来做到这一点。

我可以从 R 中的列表中操作数据: Image of the lists from Rstudio

或来自全球环境中的单个数据框

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"

我正在寻找任何解决方案,无论它们是在列表中还是在列表之外。

感谢您提供的任何帮助。

【问题讨论】:

标签: r dataframe names rbind


【解决方案1】:

我们可以用向量的子串对向量进行拆分

str1 <- ls()
lst1 <- split(str1, sub("_[^_]+$", "", str1))
lst2 <- lapply(lst1, function(x) do.call(rbind, mget(x, inherits = TRUE)))

【讨论】:

  • 谢谢阿克伦。我收到一个错误:错误:未找到 'day01_01_1of2' 的值 6. stop(gettextf("未找到 %s 的值", sQuote(x)), call. = FALSE) 5. (function (x) stop( gettextf("未找到 %s 的值", 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)))
  • 有没有办法对列表中的所有数据框做同样的事情(即 str1 实际上是所有数据框的列表)?
  • @K8Otter ls() 返回在全局环境中创建的所有对象。如果您只创建了data.frame,那么mget 将获得list 中的值。我没有正确理解你的问题
  • 本质上,第三行是否可以调整,使其在列表中的数据帧上使用 rbind,而不是在全局环境中
  • 也许你想要lapply(lst1, function(sublst) do.call(rbind, sublst))
猜你喜欢
  • 2022-11-24
  • 2021-02-13
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 2023-03-24
  • 2018-10-16
  • 2018-02-03
  • 2020-12-22
相关资源
最近更新 更多