Creating a variable depending on values of two different parameters

Advertisements

I have a question regarding how to craft a variable depending on two other variables. I need to create a dummy variable that will take the value of 1 if
Parameter1 is either A or B (but not C) and Parameter2 has a positive value. The variable needs both assumptions to upheld, otherwise will take the value of zero. This will be categorized by countries.

I have tried to illustrate this down below. What I am looking for is how to compute a variable that calculates the variable ‘Result’.

read.table(
text =
"Country, Year, Parameter1, Parameter2, Result,
US, 1, A, 12, 1,
US, 2, B, 4, 1,
US, 3, C, 2, 0,
US, 4, A, -4, 0,
UK, 1, A, -1, 0,
UK, 2, C, 2, 0,
UK, 3, B, 3, 1,
UK, 4, B, 2, 1, ", sep = ",", header = TRUE)
Country Year Parameter1 Parameter2 Result
1 US 1 A 12 1
2 US 2 B 4 1
3 US 3 C 2 0
4 US 4 A -4 0
5 UK 1 A -1 0
6 UK 2 C 2 0
7 UK 3 B 3 1
8 UK 4 B 2 1

>Solution :

We may create the condition with %in% and &, coerce the logical to binary with as.integer or +

df1$Result <- with(df1, +(Parameter1 %in% c("A", "B") & Parameter2 > 0))
df1$Result
[1] 1 1 0 0 0 0 1 1

Leave a ReplyCancel reply