[英]R if statement error: the condition has length > 1 and only the first element will be used
[英]R If statement returns “the condition has length > 1 and only the first element will be used”
我正在尝试在 R 中重现来自 Stata 的结果。 给我带来麻烦的特定行似乎很简单。
sum peace_index_score if Africa == 1
我在 R 中尝试的代码是
if (World$Africa == 1){
summary(World$peace_index_score)
}
这将返回以下错误消息:
Warning message in if (World$Africa == 1) {:
“the condition has length > 1 and only the first element will be used”
这将是
summary(World$peace_index_score[World$Africa == 1])
if Africa == 1
通过观察(如果您愿意,可以逐行)给定语法,Stata 会自动应用测试
sum peace_index_score if Africa == 1
这是if
限定符的示例。
在使用if
命令的程度上,Stata 就像 R
if Africa == 1 sum peace_index_score
被解释为
if Africa[1] == 1 sum peace_index_score
然而,Stata 中的构造是合法的,只是很少有你想要的,因为几乎总是if
命令最适合用于比较字符串或数字常量(实际上上面的命令正是这样做的)。 因此,在 Stata 中首先检查Africa
的任何值为 1 的值是合法且惯用的。
count if Africa == 1
if r(N) == 0 sum peace_index if Africa == 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.