【问题标题】:How to loop through a list in R如何遍历R中的列表
【发布时间】:2014-12-05 11:33:50
【问题描述】:

我有一个清单,可以说:

dataSet$mixed_bag <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76"))

我想遍历这个列表并根据列表的内容创建新变量。 伪代码看起来像这样。

foreach row in dataSet$mixed_bag {
    if (sapply(dataSet$mixed_bag, length) == 3) {
        dataSet$country <- dataSet$mixed_bag[[row]][1];
        dataSet$color <- dataSet$mixed_bag[[row]][2];
        dataSet$score <- dataSet$mixed_bag[[row]][3];
    } else if (sapply(dataSet$mixed_bag, length) == 2) {
       #Do something else
    } else {
       # Do nothing
    }
}

请建议我如何在 R 中执行此操作

【问题讨论】:

  • 你试过lapply吗?
  • 我做到了。我是 R 新手。所以,我不知道如何使用迭代器变量(在本例中为:row)来构建正确的语法。如果您有答案,请将其作为答案发布在下面。
  • 您可以将dput(dataSet) 的输出添加到帖子中吗?
  • 这真的取决于你想在循环中做什么..你的意思是写length(dataSet$mixed_bag[[row]])而不是sapply(dataSet$mixed_bag, length)if 中的条件以它的编写方式没有意义,因为它将向量与值进行比较,在这种情况下,您会收到警告,指出仅使用向量的第一个元素。
  • 是的。我的意思是长度(dataSet$mixed_bag[[row]])

标签: r loops


【解决方案1】:

这样的?

dataList <- list("Hello", c("USA", "Red", "100"), c("India", "Blue", "76"))
for(i in dataList)
  {print(i)}

返回:

[1] "Hello"
[1] "USA" "Red" "100"
[1] "India" "Blue"  "76"   

或:

for(i in dataList)
  {
  for(j in i)
  {print(j)}
  }

返回:

[1] "Hello"
[1] "USA"
[1] "Red"
[1] "100"
[1] "India"
[1] "Blue"
[1] "76"

【讨论】:

    猜你喜欢
    • 2016-09-19
    • 2014-09-26
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多