duckduckgoes duckduckgoes - 29 days ago 24
R Question

if then do multiple statements from SAS to R

I am new to R. Here is the SAS script that I want to replicate in R:

if a=4 or b=4 then do;
if a=1 or b=1 then news="AB";
else if a=2 or b=2 then news="BC";
else news="CD";
end;
else do;
if a=1 or b=1 then news="DF";
else news="GH";
end;


Where: a, b are variables (columns's name) of the table/data, and news is a new variable that I want to create.

I cannot find a way of ifelse or other methods to do that in R. Can you help me? Thank you!

Here is my first try on first part of the above script:

news <- ifelse(a==4 | b==4,
ifelse(a==1 | b==1, "AB",
ifelse(a==2 | b==2, "BC", "CD")))


But it did not work. The error shows
"Error in ifelse(a == 4 | b == 4, ifelse(a == 1 | b == :
argument "no" is missing, with no default"

Do you know why? Also, I am not sure how to link the second part, starting from "else do" to R. I feel like SAS script is easier to understand and write in this case than R.

Answer

ifelse is appropriate for vectors (i.e., you must test a vector and the output must be a vector of the same length as the input), if() {...} else {...} is for single conditions. Without sample input (and not really knowing SAS), I'm not sure which you're after. If a and b are single values, R Schifini's answer is good.

If a and b are vectors, then you are right to use ifelse, and your code works just fine for me. We can extend it to include the last else do statement:

test = expand.grid(a = c(1, 2, 4, 7), b = c(1, 2, 4))
a = test$a
b = test$b
news <- ifelse(a == 4 | b == 4,
               ifelse(a == 1 | b == 1, "AB",
                      ifelse(a == 2 | b == 2, "BC", "CD")),
               ifelse(a == 1 | b == 1, "DF", "GH"))

cbind(test, news)
#    a b news
# 1  1 1   DF
# 2  2 1   DF
# 3  4 1   AB
# 4  7 1   DF
# 5  1 2   DF
# 6  2 2   GH
# 7  4 2   BC
# 8  7 2   GH
# 9  1 4   AB
# 10 2 4   BC
# 11 4 4   CD
# 12 7 4   CD