我仍然在学习如何将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不是学习语言的替代品。有很多书籍,教程......当你被困住时,你应该在这里发布,并且你已经使用了所有其他资源。最好。 –