【问题标题】:Conditionally append dataframes to specific levels of a nested list有条件地将数据帧附加到嵌套列表的特定级别
【发布时间】:2019-03-19 10:18:41
【问题描述】:

我有一个嵌套列表 (mylist),并且我想将 cbind 一个数据框 (colors) 自动添加到较低级别的列表 (iris) 中,前提是列表的名称包含特定的字符串 (iris),但我遇到了一些错误。

例子:

mylist <- list(favorites=list("iris"=iris[1:5,], "mtcars"=mtcars[1:5,], "ToothGrowth"=ToothGrowth[1:5,]), misc = list("air"=airquality))
colors <- data.frame(dark = "black", light = "white", mid = "violet")

我只想将colors 附加到嵌套列表iris,本质上是:cbind(mylist$favorites$iris, colors)。我的真实数据集要大得多,无法在每个嵌套列表上手动使用cbind

这样:

> cbind.fill(mylist$favoritres$iris, colors)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species  dark light    mid
1          5.1         3.5          1.4         0.2  setosa black white violet
2          4.9         3.0          1.4         0.2  setosa black white violet
3          4.7         3.2          1.3         0.2  setosa black white violet
4          4.6         3.1          1.5         0.2  setosa black white violet
5          5.0         3.6          1.4         0.2  setosa black white violet

我目前的解决方案尝试:

mylist <- lapply(mylist, function(x) {
    if(grepl("iris", x$favorites)==TRUE){
        x$favorites <- lapply(x$favorites, function(y) cbind(y, colors))
        }; x
    })

哪个会引发错误:

if (grepl("iris", x$favorites) == TRUE) { 中的错误: 参数长度为零

【问题讨论】:

  • cbind.fill,我希望colors 的每一列中的条目与iris 的所有行一起传播。更新示例

标签: r dataframe apply lapply mapply


【解决方案1】:

我们可以创建一个逻辑条件来追加

library(rowr)
mylist2 <- lapply(mylist, function(x)  {
       i1 <- names(x) == "iris"
        x[i1] <- lapply(x[i1], function(y) cbind.fill(y, colors))
        x
   })

【讨论】:

  • 这可行,但有没有避免创建新列表的解决方案?
【解决方案2】:

这是一个递归解决方案,无论它在您的列表中嵌套多深,都会找到“iris”:

library(rowr)

bind_search <- function(the_list, the_df, matching_name) {

  for (n in names(the_list)) {

    if (n == matching_name && is.data.frame(the_list[[n]])) {
      the_list[[n]] <- cbind.fill(the_list[[n]], the_df)
      return(the_list)
    }

    the_list[[n]] <- bind_search(the_list[[n]], the_df, matching_name)
    return(the_list)
  }
}

mylist2 <- bind_search(mylist, colors, 'iris')

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 2015-08-10
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2021-05-17
    • 2015-09-28
    • 2021-07-02
    相关资源
    最近更新 更多