【发布时间】:2018-07-13 18:53:36
【问题描述】:
我编写了以下嵌套 for 循环,它应该遍历数据框 df,如果行 q 中有 a,则在 a 列中创建 1。通常,对于 a、b 和 c 列,如果 q 列中的条目与列名匹配,则 a、b 和 c 列应通过具有一个来表示。
由于我无法很好地描述它,这里有一段代码来说明我的意思。
此时,生成的 df 仅在 c 列中的相应第三行中具有 1,但在 a 或 b 列中没有。
df = data.frame(q=c("a","b","c"),a=c(0,0,0),b=c(0,0,0),c=c(0,0,0))
for (x in nrow(df)) {
for (y in ncol(df)) {
if (colnames(df[y]) == df$q[x]) {
df[x,y] = 1}
}}
A picture of the intended output (whereas the red "1s" do not appear at this moment:
此外,我正在处理的实际数据框大约是 100 000 行和 100 列。
谢谢!
【问题讨论】:
标签: r for-loop dataframe nested nested-loops