如何为" Select statement in Sas"编写等效的 R 代码

  • 本文关键字:代码 Sas Select statement in r sas
  • 更新时间 :
  • 英文 :


我正在SAS中编写代码,现在我需要将其转换为R我已经粘贴了我的r代码,但我知道这是不对的。我需要使用类似"在SAS中选择"的东西。请帮我将此sas代码转换为R

data t2; set t; by nhi ass_yr ass_mth;
R_G_Right = G1_Right;
M_G_Right = G1_Right_Maculopathy;
R_G_Left = G1_Left;
M_G_Left = G1_Left_Maculopathy;
*   if G2 performed, use this   ;
if G2_Right ne . then R_G_Right = G2_Right;
if G2_Right_Maculopathy ne . then M_G_Right = G2_Right_Maculopathy;
if G2_Left ne . then R_G_Left = G2_Left;
if G2_Left_Maculopathy ne . then M_G_Left = G2_Left_Maculopathy;
*   collapse grades         ;
*   0 - remains 0           ;
*   1-2 ->      1           ;
*   3 ->        2           ;
*   4-5-6 ->    3           ;
select (R_G_Right);
when (.) retgradeR = 0;
when (0) retgradeR = 0;``
when (1) retgradeR = 1;
when (2) retgradeR = 1;`enter code here`
when (3) retgradeR = 2;
otherwise retgradeR = 3;
end;

您可以使用dplyr以这种方式完成我没有翻译R中的by语句,因为它在代码的后面没有任何影响。基本上所有的东西都可以变成mutate函数,case_when取代了selectSAS代码。

library(dplyr)
t2 <- t %>% mutate(R_G_Right = G1_Right,
M_G_Right = G1_Right_Maculopathy,
R_G_Left = G1_Left,
M_G_Left = G1_Left_Maculopathy,
R_G_Right = ifelse(!is.na(G2_Right),G2_Right,R_G_Right),
M_G_Right = ifelse(!is.na(G2_Right_Maculopathy),G2_Right_Maculopathy,M_G_Right),
R_G_Left = ifelse(!is.na(G2_Left),G2_Left,R_G_Left),
M_G_Left = ifelse(!is.na(G2_Left_Maculopathy),G2_Left_Maculopathy,M_G_Left),
retgradeR =  case_when(
is.na(R_G_Right)| R_G_Right==0  ~ 0,
R_G_Right %in% c(1,2) ~ 1,            
R_G_Right==3 ~2,
TRUE ~ 3)
)

最新更新