我仍然在學習如何將SAS代碼翻譯成R,並收到警告。我需要了解我犯的錯誤。我想要做的是創建一個總結和區分人口三大地位的變量:大陸,海外,外國人。 我有2個變量數據庫:嵌套ifelse語句
- ID國籍:
idnat
(法國,外國人),
如果idnat
是法國人,則:
- ID出生地:
idbp
(大陸,殖民地,海外)
我想總結一下信息米idnat
和idbp
到一個新的變量,名爲idnat2
:
- 狀態:K(內地,海外,外國人)
所有論文變量使用 「字符類型」。
結果預計將在列idnat2:
idnat idbp idnat2
1 french mainland mainland
2 french colony overseas
3 french overseas overseas
4 foreign foreign foreign
這裏是我的SAS代碼,我想中的R翻譯:
if idnat = "french" then do;
if idbp in ("overseas","colony") then idnat2 = "overseas";
else idnat2 = "mainland";
end;
else idnat2 = "foreigner";
run;
這裏是我的R中的嘗試:
if(idnat=="french"){
idnat2 <- "mainland"
} else if(idbp=="overseas"|idbp=="colony"){
idnat2 <- "overseas"
} else {
idnat2 <- "foreigner"
}
我收到這樣的警告:
Warning message:
In if (idnat=="french") { :
the condition has length > 1 and only the first element will be used
有人建議我使用「嵌套ifelse
」,而不是它的容易,但得到更多的警告:
idnat2 <- ifelse (idnat=="french", "mainland",
ifelse (idbp=="overseas"|idbp=="colony", "overseas")
)
else (idnat2 <- "foreigner")
按照警告消息長度大於1,所以只有第一個括號之間的內容纔會被考慮。對不起,但我不明白這個長度與這裏有什麼關係?任何人都知道我錯在哪裏?
你不應該混'ifelse'和'else'。 – Roland
@ Roland你說得對,謝謝你的建議,我只是把結果。我想要的只是在列idnat2,如果它清楚。 @KarlForner謝謝你,這正是我想用簡單的例子做的事情,但是我真的很苦惱於「R」。我試圖在SPSS上做同樣的事情,它更簡單。 – balour
我的觀點是,SO不是學習語言的替代品。有很多書籍,教程......當你被困住時,你應該在這裏發佈,並且你已經使用了所有其他資源。最好。 –