相关疑难解决方法(0)

嵌套的ifelse语句

我还在学习如何将SAS代码翻译成R,然后收到警告.我需要了解我犯错误的地方.我想要做的是创建一个变量来总结和区分人口的3种状态:大陆,海外,外国人.我有一个包含2个变量的数据库:

  • 国籍:( 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
Run Code Online (Sandbox Code Playgroud)

这是我要在R中翻译的SAS代码:

if idnat = "french" then do;
   if idbp in ("overseas","colony") then idnat2 = "overseas";
   else idnat2 = "mainland";
end;
else idnat2 = "foreigner";
run;
Run Code Online (Sandbox Code Playgroud)

这是我在R中的尝试:

if(idnat=="french"){
    idnat2 <- "mainland"
} else if(idbp=="overseas"|idbp=="colony"){
    idnat2 <- "overseas"
} else {
    idnat2 <- …
Run Code Online (Sandbox Code Playgroud)

if-statement nested r sas

53
推荐指数
5
解决办法
17万
查看次数

标签 统计

if-statement ×1

nested ×1

r ×1

sas ×1