Home > Net >  Generate new variable on multiple conditions
Generate new variable on multiple conditions

Time:12-30

I have this dataset:

$ id : num 805 805 805 851 851 851...

$ educ_cat: num 5 5 5 5 5 6 6 6 6 6 3 3 3 3 ...

$ pol_sof : num 1 1 1 0.8 1 1 1 1 0.8 1 0.6 0.4 0.4 ...

What I want is to create a logical variable fra 0-1, based on two criteria:

If educ_cat = 5 or 6 AND pol_sof>0.6 then respondent should have 1. Otherwise respondent should get a 0.

How to obtain this in R?

Thanks!

CodePudding user response:

Use logical operations with %in% and >, put them together with & and coerce the logical value to integers

df$fra <- as.numeric(df$educ_cat %in% c(5, 6) & df$pol_sof > 0.6)

CodePudding user response:

You can try this.

df1$fra <- df1$educ_cat == 5 | df1$educ_cat == 6 & df1$pol_sof > 0.6
# or
df1$fra2 <- (df1$educ_cat == 5 | df1$educ_cat == 6 & df1$pol_sof > 0.6)*1
df1
   educ_cat pol_sof   fra fra2
1         5     1.0  TRUE    1
2         5     1.0  TRUE    1
3         5     1.0  TRUE    1
4         5     0.8  TRUE    1
5         5     1.0  TRUE    1
6         6     1.0  TRUE    1
7         3     0.3 FALSE    0
8         6     1.0  TRUE    1
9         6     0.1 FALSE    0
10        6     0.8  TRUE    1
11        6     1.0  TRUE    1
12        3     0.6 FALSE    0
13        3     0.4 FALSE    0
14        3     0.4 FALSE    0

Data

educ_cat <- c(5, 5, 5, 5, 5, 6, 3, 6, 6, 6, 6, 3, 3, 3)
pol_sof <- c(1, 1, 1, 0.8, 1, 1, 0.3, 1, 1, 0.8, 1, 0.6, 0.4, 0.4)
df1 <- data.frame(educ_cat, pol_sof)

CodePudding user response:

We could use an ifelse statement with the condition:

library(dplyr)

df1 %>% 
  mutate(fra = ifelse(educ_cat==5 | educ_cat==6 & pol_sof > 0.6, TRUE, FALSE))
  educ_cat pol_sof   fra
1         5     1.0  TRUE
2         5     1.0  TRUE
3         5     1.0  TRUE
4         5     0.8  TRUE
5         5     1.0  TRUE
6         6     1.0  TRUE
7         3     0.3 FALSE
8         6     1.0  TRUE
9         6     1.0  TRUE
10        6     0.8  TRUE
11        6     1.0  TRUE
12        3     0.6 FALSE
13        3     0.4 FALSE
14        3     0.4 FALSE
  • Related