R - 如果删除列则无限循环
R - infinite loop if for dropping columns
我正在尝试从数据框中删除无用的列。我使用了一个带有 if 语句的 while 循环,它似乎永远不会离开 if 语句:
it = 1
while (it < ncol(testing))
{
if ("drop" %in% CategOfData[it,])
{testing[,it]<-NULL}
else it = it + 1
}
只要 if 循环没有嵌套在 while 循环中,它就可以工作。
测试是我的数据框,包含 400 行和 12 列,
CategOfData是一个12行2列的数据框,CategOfData包含了我的df"testing"的header和它的类别,3行包含了单词"drop"
我通过将 {testing[it]<-NULL} 替换为 {jkl = jkl + 0.5} 来测试此代码,
代码又是 运行 长,我把它剪短了,询问控制台 jkl 的值是多少,它返回了一个远远超过 800 000 的数字,而它应该返回 2.5 (1 + 3*0.5)
我不明白为什么它永远不会进入代码的 else 部分。这使得 while 循环无限,因为 "it" 从不递增
我会使用 for 循环,但 R 不同意,因为我正在删除列。
CategOfData 的类型:
> CategOfData [1,]
header x
"PIERRE.MARIE" "drop"
和"testing"
> head(testing[,1])
[1] PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE
Levels: LAURENNE PIERRE-MARIE
你能帮我找出问题所在吗?
我试过这个
it = 1
rem = ncol(testing)
while (it < rem)
{
if ("drop" %in% CategOfData2[it,])
{testing[,it]<-NULL
CategOfData2 = CategOfData2[-it,]
rem = rem - 1
}
it = it + 1
}
有效~好的,但不会删除掉落的最后一列
你的问题用两行R代码就可以解决:
drop <- apply(CategOfData, 1, function(x) { "drop" %in% x })
testing <- testing[, !drop]
这是一个很好的例子,说明了当你正确使用 R 时它所具有的那种力量。
我正在尝试从数据框中删除无用的列。我使用了一个带有 if 语句的 while 循环,它似乎永远不会离开 if 语句:
it = 1
while (it < ncol(testing))
{
if ("drop" %in% CategOfData[it,])
{testing[,it]<-NULL}
else it = it + 1
}
只要 if 循环没有嵌套在 while 循环中,它就可以工作。
测试是我的数据框,包含 400 行和 12 列,
CategOfData是一个12行2列的数据框,CategOfData包含了我的df"testing"的header和它的类别,3行包含了单词"drop"
我通过将 {testing[it]<-NULL} 替换为 {jkl = jkl + 0.5} 来测试此代码, 代码又是 运行 长,我把它剪短了,询问控制台 jkl 的值是多少,它返回了一个远远超过 800 000 的数字,而它应该返回 2.5 (1 + 3*0.5)
我不明白为什么它永远不会进入代码的 else 部分。这使得 while 循环无限,因为 "it" 从不递增
我会使用 for 循环,但 R 不同意,因为我正在删除列。
CategOfData 的类型:
> CategOfData [1,]
header x
"PIERRE.MARIE" "drop"
和"testing"
> head(testing[,1])
[1] PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE PIERRE-MARIE
Levels: LAURENNE PIERRE-MARIE
你能帮我找出问题所在吗?
我试过这个
it = 1
rem = ncol(testing)
while (it < rem)
{
if ("drop" %in% CategOfData2[it,])
{testing[,it]<-NULL
CategOfData2 = CategOfData2[-it,]
rem = rem - 1
}
it = it + 1
}
有效~好的,但不会删除掉落的最后一列
你的问题用两行R代码就可以解决:
drop <- apply(CategOfData, 1, function(x) { "drop" %in% x })
testing <- testing[, !drop]
这是一个很好的例子,说明了当你正确使用 R 时它所具有的那种力量。