将 SAS 语言翻译成 R 语言:创建一个新变量

Translating SAS language to R language: Creating a new variable

我有一段sas代码,想翻译成R,有兴趣根据其他变量的条件创建变量。

data wp;
set wp;

if totalcriteria =>3 and nonecom=0 then content=1;
if totalcriteria =>3 and nonecom=1 then content=0;
if totalcriteria  <3 and nonecom=0 then content=0;
if totalcriteria  <3 and nonecom=1 then content=0;
run;

这是我的代码。我的 "content" 条件已更改,我想将 sas 代码转换为 R 以希望替换下面代码的 "mutate" 行或适合使用以下代码:

wpnew <- wp %>%
   mutate(content = ifelse (as.numeric(totalcriteria >= 3),1,0))%>%
   group_by(district) %>%
   summarise(totalreports =n(),
             totalcontent = sum(content),
             per.content=totalcontent/totalreports*100)

你能帮我把这段SAS代码翻译成R语言吗?提前谢谢你。

这里是 dput 输出

structure(list(Finances = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), Exercise = c(0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), Relationships = c(0, 0, 0, 0, 0, 0, 0, 1, 0, 
0, 0, 0, 0, 0, 0, 0), Laugh = c(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 0, 1), Gratitude = c(0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 
0, 0, 0, 0, 0, 1), Regrets = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 
0, 0, 0, 0, 0, 0), Meditate = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0), Clutter = c(0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 
0, 0, 1, 0, 0, 0), Headache = c(0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 
0, 0, 1, 0, 0, 0), Loss = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 
0, 0, 0, 0, 0), Anger = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
1, 0, 0, 0), Difficulty = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), nonecom = c(1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 
1, 0, 1, 1, 0), Othercon = c(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), totalcriteria = c(0, 0, 2, 3, 2, 0, 0, 4, 3, 
0, 0, 0, 3, 0, 0, 2)), class = "data.frame", row.names = c(NA, 
-16L))

这就是我想要的样子

V1   V2   V3...V12  nonecom  Othercon  totalcriteria  content  
1     1   1     0      1        0           3             0
0     0   1     0      0        0           8             1
1     0   0     0      0        1           2             0
1     0   1     0      1        0           1             0

我使用 case_when 只是因为我发现它在语法方面更相似。您当前的方法仅测试 IF 条件的第一部分,而不测试关于 nonecom.

的第二部分
wpnew <- wp %>%
   mutate(content = case_when(sum.content >= 3 & nonecom == 0 ~ 1,
                              TRUE ~ 0))