Ani
Ani

Reputation: 338

Translating SAS language to R language: Creating a new variable

I have a sas code and I want to translate into R. I am interested in creating variables based on the conditions of other variables.

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;

This is a code I have in. My conditions for "content" as changed and I would like to translate the sas code to R to hopefully replace the "mutate" line of the code below or fit in with the code below:

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)

Can you help me translate this SAS code to R language. Thank you in advance.

Here is the dput output

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))

This is what I would like it to look like

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

Upvotes: 0

Views: 143

Answers (1)

Reeza
Reeza

Reputation: 21274

I use case_when just because I find it more similar in terms of syntax. Your current approach only tests the first part of the IF condition, not the second part regarding nonecom.

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

Upvotes: 0

Related Questions