rif-statementconditional-statements

R If then do - how to create variables based on the condition


As a dedicated SAS user, I struggle with understanding if-then logic in R.

Say, I have the following data frame:

test<-data.frame("year" = c(2018, 2019),
             "var1"=c(1,2),
             "var2"=c(3,4),
             "var3"=c(5,6),
             "var4"=c(7,8),
             "var5"=c(9,10),
             "var6"=c(11,12))

Now, I want to create two additional variables in the following way:

if year is 2018 then extra_var1=var1+var2, extra_var2=var2+var3 if year is 2019 then extra_var1=var4+var5, extra_var2=var5+var6

In SAS I would do:

data test;
set test;
if year=2018 then do;
extra_var1=var1+var2;
extra_var2=var2+var3;
end;
if year=2019 then do;
extra_var1=var4+var5;
extra_var2=var5+var6;
end;
run;

How to do it in R? Is there any other way than a nested ifelse?


Solution

  • You don't need nested if commands.

    if (test$year == 2018)
    {
      test$extra_var1 <- test$var1 + test$var2
      test$extra_var2 <- test$var2 + test$var3
    }
    
    if (test$year == 2019)
    {
      test$extra_var1 <- test$var4 + test$var5
      test$extra_var2 <- test$var5 + test$var6
    }
    

    which gives:

      year var1 var2 var3 var4 var5 var6 extra_var1 extra_var2
    1 2018    1    3    5    7    9   11          4          8
    2 2019    2    4    6    8   10   12          6         10