[英]convert sas if-else statement to R
I have a SAS code similar to the below logic. 我有一个类似于以下逻辑的SAS代码。 I would like to convert it to R script using if-else or ifelse method. 我想使用if-else或ifelse方法将其转换为R脚本。 Here is the SAS code example: 这是SAS代码示例:
if cat1=1 then do;
if cat2 eq 'U' then do;
if var1 =. then var1 = var3;
end;
else if cat2='A' then do;
if var1 =. then var1=var2;
end;
end;
else do;
if cat2 eq 'U' then do;
if cat3 = 'NC' then do;
if var1 =. then do;
if var2 ge 4.0 then var1 =1.15;
else if var2 le 4.0 then var1 = 10.0;
else var1 = 6.1;
end;
end;
end;
end;
Here is the converted R script code. 这是转换后的R脚本代码。 However, the last step (df4) overwrite all the previous steps. 但是,最后一步(df4)将覆盖之前的所有步骤。 Is there a better way to convert this logic into R if - else statement. 是否有更好的方法将此逻辑转换为R if-else语句。
df <- data.frame(cat1 = c(rep(1,3), rep(0,4)),
cat2 = c(rep('U',2), rep('A',3), 'U', 'U'),
cat3 = c(rep('NC',2), rep('RF',2), 'NC', 'NC', 'NC'),
var1 = c(rep(NA,5),.14, NA),
var2 = c(rep(NA,2), 4.5, 2.3, 8.5, 3.4, 2.4),
var3 = c(rep(2.6, 2), 3.9, NA, 4.2, .012, NA))
df2 <- transform(df,
var1 = ifelse(is.na(var1) & cat1 ==1 & cat2 == 'U', var3, var1)
)
df3 <- transform(df2,
var1 = ifelse(is.na(var1) & cat1 ==1 & cat2 == 'A', var2, var1)
)
df4 <- transform(df3,
var1 = ifelse(is.na(var1) & cat2 == 'U' & cat3 == 'NC' & var2 >= 4.0, 1.15,
ifelse(var2 <= 4.0, 10.0, 6.1))
)
Please help? 请帮忙?
I generally try to make "targeted assignments", ie assignments only into the locations that match the current criteria. 我通常会尝试进行“目标分配”,即仅分配到与当前条件匹配的位置。 That way I can avoid the problems with overwriting when I modify the entire vector with nested ifelse
's that I have not adequately debugged: 这样,当我使用嵌套的ifelse
修改整个向量时,就可以避免覆盖问题,因为我没有进行足够的调试:
df$var1[ with(df, is.na(var1) & cat1 ==1 & cat2 == 'U' )] <- df$var3
df$var1[ with(df,(is.na(var1) & cat1 ==1 & cat2 == 'A') ] <- df$var2
df$var1[ with(df, is.na(var1) & cat2 == 'U' & cat3 == 'NC') ] <-
with( df[ with(df, is.na(var1) & cat2 == 'U' & cat3 == 'NC') , ],
ifelse( var2 >= 4.0, 1.15,
ifelse(var2 <= 4.0, 10.0, 6.1))
)
I'm not sure I got the logic correct. 我不确定我的逻辑是否正确。 I just copied your R conditionals into the selections. 我只是将您的R条件语句复制到选择中。
df DF
cat1 cat2 cat3 var1 var2 var3
1 1 U NC 2.60 NA 2.600
2 1 U NC 2.60 NA 2.600
3 1 A RF NA 4.5 3.900
4 0 A RF NA 2.3 NA
5 0 A NC NA 8.5 4.200
6 0 U NC 0.14 3.4 0.012
7 0 U NC 10.00 2.4 NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.