【问题标题】:Populating rows of a dataframe with a changing index / updating an index in a loop使用不断变化的索引填充数据帧的行/在循环中更新索引
【发布时间】:2019-12-02 01:00:44
【问题描述】:

对于这将是多么棘手的描述和难以通过示例重现,提前致歉,并提前感谢您的通读!

我正在尝试使用可以返回单个值或 多个 值的自定义函数有条件地填充空数据框。每个值必须是数据框中的一行。多个值来自嵌套列表传递给函数的事实,其中一些只有 1 个列表,其中一些有 9 或 10 个子列表。

通常,一个带有索引的简单 for 循环就可以了:

for (i in 1:nrow(df)){
    df[i,] <- function(x[i])
}

但是因为我的函数可以返回多个值,每个值都必须是一行,所以索引是不断变化的,我不知道如何更新它。基本上我一直在尝试的是:

for (i in 1:nrow(df)){    # where df is the empty df I want to fill
df[i,] <- if(another.corresponding.df == 1){function(x[i])    # if there is only 1 nested list at index i, apply the function and write the returned value to the corresponding row
  } else {
       for (j in 1:another.corresponding.df[i]){   # if there are multiple nested lists at index i, loop through j nested lists
          if(j == 1) {df[i,] <- function(x[i][j])  # use index 1 as the row
           } else { df[i+1,] <- function(x[i][j])  # update the row number based on however many j nested lists produced values
      }
  }
}

^ 这一直有效,直到遇到 first 多值索引,之后原始索引被丢弃,我收到以下信息: Error in x[[jj]][iseq] &lt;- vjj : replacement has length zero

例如,假设我使用列表 x 来构建我的数据框,其中 x 是 3 个子列表的列表:x[1] 有 1 个值,x[2] 有 2 个值,x[3] 有1 个值:

x <- list(2:7, list(12:15, 15:17), 10:14)

x
[[1]]
[1] 2 3 4 5 6 7

[[2]]
[[2]][[1]]
[1] 12 13 14 15

[[2]][[2]]
[1] 15 16 17

[[3]]
[1] 10 11 12 13 14

我想将我的函数应用于此列表的 所有 元素,以填充我的数据框,使其总共有 4 行,其中

row 1 = function(x[1])
row 2 = function(x[2][1]) 
row 3 = function(x[2][2])
row 4 = function(x[3])

因此,一旦我应用上面代码的 df[i+1,] 部分,第 3 行将填充 x[2][2] 的值,因此我不能使用 i = 3 来获取 x[3]。

我需要根据我运行的许多嵌套列表迭代更新索引值——我该怎么做?

【问题讨论】:

标签: r list loops dataframe


【解决方案1】:

假设应用于每个列表的函数是fun1,而我们拥有的列表称为lst1,我们可以尝试这样的操作

apply_fun <- function(x) {
   if (is.list(x)) 
     do.call(rbind, lapply(x, fun1))
   else fun1(x)
}

do.call(rbind, lapply(lst1, apply_fun))

apply_fun 检查它是否是嵌套列表并将fun1 应用于嵌套列表的每个元素。

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2017-05-17
    • 2021-07-23
    • 1970-01-01
    • 2019-08-12
    • 2018-01-18
    • 1970-01-01
    • 2023-03-05
    • 2013-05-08
    相关资源
    最近更新 更多