【问题标题】:Extracting different-sized elements from a list within a loop in R从R中循环内的列表中提取不同大小的元素
【发布时间】:2020-04-23 13:52:03
【问题描述】:

我有一组 94 个列表,每个列表都有不同数量的元素,每个元素的长度也不同。下面显示了其中一个列表的示例

 > head(output)
 $clusters
 $clusters[[1]]
 [1] "cookie" "duckie" "seven"  "sticky"

 $clusters[[2]]
  [1] "a"      "ah"     "ball"   "blue"   "boo"    "boy"    "bunny"  "bye"    "eight"  "eye"    
 "five"   "go"     "goose"  "he's"   "hello"  "hey"    "hi"     "is"     "it"     "it's"   "leaf"   
 "meow"   "moon"   "no"    
 [25] "oh"     "one"    "ooh"    "pop"    "shh"    "six"    "that"   "this"   "towel"  "two"    
 "uhoh"   "wee"    "what"   "what's" "whoa"   "wow"    "yay"    "yellow" "yes"   


 $edges
 [1] 44 45

我正在创建一个提取部分列表的循环 - 在上面显示的示例中,我想提取 clusters[[1]]clusters[[2]]

我有以下代码:

   for (i in length(output)) {  
     values <- output[[1]][i]
         }

但这只会返回第二个元素clusters[[2]]。我想做的是将每个列表中的元素保存为单独的数据框,如下例所示:

 library(tibble)

 values1 <- tribble(~V1,
           "cookie",
           "duckie",
           "seven",
           "sticky") 

 values2 <- tribble(~V1,
           "a",
           "ah",
           "ball",
           "blue",
           "boo",
           "boy",
           "bunny",
           "etc") 

我怎样才能做到这一点,以便我可以通过 94 个不同大小的列表快速运行它?

【问题讨论】:

  • length(output) 不只是一个数字,而您需要1:length(output) 吗?
  • 好的,我试过了,它将output 中的两个元素连接到一个数据帧。我想要做的是为每个元素创建一个单独的数据框。我已经编辑了问题以更清楚地显示这一点。
  • 你想对单独的数据框做什么?赋值吗?保存?在循环中使用它?
  • 这个循环是一个更大的脚本的一部分,它使用lapply() 在我的数据中运行一个函数。获得一组数据框后,我想在函数中使用它们来创建一个大型数据集,该数据集包含来自 94 个列表中的每一个列表的信息。
  • 听起来你实际上需要一个数据框列表。在这种情况下,根本不需要forlapply(output$clusters, function(cl)data.frame(V1 = cl, stringsAsFactors = FALSE)) 可以解决问题。

标签: r list for-loop


【解决方案1】:

如果您想为集群的每个条目处理一列数据框,您可以这样:

for (cluster_number in seq_along(output$clusters)) {
  current_cluster_df <- data.frame(
    V1 = output$clusters[[cluster_number]],
    stringsAsFactors = FALSE
  )
  # Do whatever you want with the data frame
}

这里的关键是访问output$cluster[i] 以获取所有有效索引。 seq_along(list) 将返回这些有效索引的向量(想想更强大的 1:length(list) 版本)。

您的原始代码有两个问题:1. length(output) 不是 length(output$clusters) 和 2. 您使用 for (i in length(output))。这是一个 for 循环,其中 i 仅循环一个值,即 length(output),恰好是 2,这也是 output$clusters 的有效索引。

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 2021-12-05
    • 1970-01-01
    • 2015-10-02
    • 2013-05-29
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多