![](/img/trans.png)
[英]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.