循环访问R中的列表的for循环内的if循环? [英] if loop inside a for loop which iterates over a list in R?
问题描述
使用R完成了初学者的学习,我环顾了四周,但找不到所需的东西.
Complete beginner with R and I've looked around quite a bit but I can't find what I need.
我有一个for循环,它循环访问值列表.我想在该for循环中放入一个if循环,如下所示:
I have a for loop which iterates over a list of values. I want to put an if loop within that for loop, like this:
for (i in list){
if (i>200){
print (i)
}
}
这将返回以下警告:
"警告消息: 如果(i> 200){: 条件的长度> 1,并且只会使用第一个元素.
"Warning message: In if (i > 200) { : the condition has length > 1 and only the first element will be used"
可以肯定的是,if循环仅检查列表中第一个元素的条件.
and sure enough, the if loop only checks the condition on the very first element in the list.
我知道这可能是因为for循环在R中未返回任何内容,但是解决方法是什么.我该如何解决?
I understand that this might be because the for loops don't return anything in R, but what's the workaround. How do I solve this?
感谢您的帮助.
推荐答案
for (i in 1:20){
if (i>10) print(i)
}
通常,条件为true或false:1或0.因此条件必须始终为1.
In general, conditions are either true or false: 1 or 0. So the condition must always have length 1.
这篇关于循环访问R中的列表的for循环内的if循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!