我仍在学习如何将SAS代码翻译成R,并且我收到了警告。我需要理解我犯了哪些错误。我想要做的是创建一个变量,总结并区分人口的三种状态:本地人、海外人和外国人。我有一个包含两个变量的数据库:
- 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
以下是我要将其翻译为R语言的SAS代码: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
混用。 - Rolandif
vs.ifelse
),我投了赞成票,因为当我开始使用R时,我也遇到了完全相同的问题。《R介绍》中没有清楚地说明,R语言定义中也没有关于ifelse
的内容,只有在R For Dummies中有一些示例。还有其他描述if
和ifelse
差异的来源吗? - Tomas Greif