【发布时间】:2017-08-08 03:36:50
【问题描述】:
我正在尝试将数据帧中的数值设置为 R 中 for 循环中的迭代器条件,但我无法使其工作。
脚本的思路是这样的:
- 循环遍历数据框中的行
- 对于每一行,循环一个块的次数与该行中的值所指示的一样多
例如,我有一个名为 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:as.numeric(events[i,2]1:events$Years[i]1:as.integer(events[i,2])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