【问题标题】:How do you use a value from a data frame as the for loop iterator in R?如何使用数据框中的值作为 R 中的 for 循环迭代器?
【发布时间】:2017-08-08 03:36:50
【问题描述】:

我正在尝试将数据帧中的数值设置为 R 中 for 循环中的迭代器条件,但我无法使其工作。

脚本的思路是这样的:

  1. 循环遍历数据框中的行
  2. 对于每一行,循环一个块的次数与该行中的值所指示的一样多

例如,我有一个名为 events 的数据框,如下所示:

Row     Event        Years
 1        1           10
 2        2           7

我想运行以下循环来执行上面的脚本:

for (i in 1:nrow(events)){
  for(j in 1:events[i,2]{
    print(paste('The event number is',i,'and the year number is',j))
  }
}

我正在寻找的结果如下所示:

[1] "The event number is 1 and the year number is 1."
[1] "The event number is 1 and the year number is 2."
[1] "The event number is 1 and the year number is 3."
[1] "The event number is 1 and the year number is 4."
[1] "The event number is 1 and the year number is 5."
[1] "The event number is 1 and the year number is 6."
[1] "The event number is 1 and the year number is 7."
[1] "The event number is 1 and the year number is 8."
[1] "The event number is 1 and the year number is 9."
[1] "The event number is 1 and the year number is 10."
[1] "The event number is 2 and the year number is 1."
[1] "The event number is 2 and the year number is 2."
[1] "The event number is 2 and the year number is 4."
[1] "The event number is 2 and the year number is 5."
[1] "The event number is 2 and the year number is 6."
[1] "The event number is 2 and the year number is 7."

但我得到的结果是:

[1] "The event number is 1 and the year number is 1."
[1] "The event number is 2 and the year number is 1."
[1] "The event number is 2 and the year number is 2."

出于测试目的,我尝试了以下代码,它按照我想要的方式工作......

for (i in 1:nrow(events)){
  for(j in 1:10){
    print(paste('The event number is',i,'and the year number is',j))
  }
}

...所以我已经尝试了所有可以动态复制10 值的方法。

我是 R 新手,但我对编程并不陌生;从如何调用索引到值的类型,再到使用dim() 设置和获取维度,以及下面列出的其他方法,我已经尝试了所有方法:

  1. 1:as.numeric(events[i,2]
  2. 1:events$Years[i]
  3. 1:as.integer(events[i,2])
  4. 1:as.factor(events[i,2])

我认为我将迭代器视为单个值(如整数),而不是像因子或向量这样的 R 构造,这就是我遗漏的地方。我还阅读了有关使用apply 函数解决此类问题的信息,但我不熟悉它的用法,所以我想先尝试解决for 循环。

有人知道我这里有什么问题吗?为此,我整天都在拔头发!

提前感谢您的帮助。

【问题讨论】:

  • 看起来您的 Years 列是第 3 列而不是第 2 列。您确定您正确访问了 Years 值吗?检查str(events) 有助于确保您了解数据的结构。
  • 执行for(j in 1:events[i,"Years"]) {} 通常风险较小,这样数据集中的顺序就无关紧要了。
  • @Marius 该行仅用于说明,它不是数据框中的列。

标签: r dataframe nested-loops


【解决方案1】:

试试:

df <- read.table(header = TRUE, text = "Row     Event        Years
1        1           10
2        2           7")

Count <- do.call("c", lapply(df$Years, function(x) seq(1, x)))
df <- df[rep(df$Event, df$Years) ,]
df <- cbind(df, Count)

paste("The event number is", df$Event, "and the year number is", df$Count)

如果可以矢量化,我认为 for 循环不是一个好主意。

【讨论】:

  • 谢谢,@r.user.05apr。我稍微弄乱了你的代码以使其工作(我的数据框与问题中的示例有点不同)但我确实让它与lapply的排序策略和Count的附加一起工作向量。
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-08
相关资源
最近更新 更多