Reputation: 307
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?
Upvotes: 3
Views: 5960
Reputation: 1800
you can use the ifelse base r function
var = ifelse(test, yes, no)
you can make some nested statements
ifelse(test1, yes,
ifels(test2,yes,no))
attach(test)
test$extra_var1 =
ifelse(test$year == 2018,test$var1 + test$var2,
ifelse(test$year == 2019,test$var4 + test$var5,NA))
test$extra_var2 =
ifelse(test$year == 2018,test$var2 + test$var3,
ifelse(test$year == 2019,test$var5 + test$var6,NA))
which gives in your case
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 18 22
Upvotes: 2
Reputation: 11016
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
Upvotes: 1