Home > Blockchain >  Creating a variable depending on values of two different parameters
Creating a variable depending on values of two different parameters

Time:11-15

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

CodePudding user response:

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

CodePudding user response:

Another option is

within(df, Result <- as.numeric(!(Parameter1 == 'C' | Parameter2 < 0)))
  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

CodePudding user response:

Here's another approach by multiplying the conditions; I am using dplyr and magrittr packages just for a different look but this can be also applied in the base solutions provided by others.

library(dplyr)
library(magrittr)


df1 %<>% 
  mutate(Result = (Parameter1 != "C") * (Parameter2 > 0))    
#>   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

Data:

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)->df1
  • Related