Home > Net >  Create a new variable based on condition of consecutive observations from other variables
Create a new variable based on condition of consecutive observations from other variables

Time:06-01

In the following dataframe df I want to create a new variable var_new== 1 for every second trial Trial ==2 of each 'Part_ID' that the previous observation has var_1== 1 and the current observation has var_1== 0. All the other values in the new variable will be zero;var_new == 0.

Part_ID<- c(1,1,2,3,4,5,5,6,6,7,7,8,8,9,10)
var_1<- c(1,0,0,1,0,1,0,1,0,0,0,1,0,1,0)
Trial<- c(1,2,1,1,1,1,2,1,2,1,2,1,2,1,2)
df <- data.frame(Part_ID, var_1, Trial)

CodePudding user response:

Using dplyr:

library(dplyr)
    
df %>% 
  mutate(var_new = ifelse(Trial == 2 & var_1 == 1, 1, 0))

Using Base R:

df$var_new <- ifelse(df$Trial == 2 & df$var_1 == 1, 1, 0)

Which gives us:

# A tibble: 15 × 4
# Groups:   Part_ID [10]
   Part_ID var_1 Trial var_new
     <dbl> <dbl> <dbl>   <dbl>
 1       1     0     1       0
 2       1     0     2       0
 3       2     0     1       0
 4       3     1     1       0
 5       4     0     1       0
 6       5     0     1       0
 7       5     1     2       1
 8       6     0     1       0
 9       6     1     2       1
10       7     0     1       0
11       7     0     2       0
12       8     0     1       0
13       8     1     2       1
14       9     1     1       0
15      10     0     2       0

CodePudding user response:

data.table option with fifelse:

library(data.table)
setDT(df)[, var_new := fifelse(Trial == 2 & var_1 == 1, 1, 0), by = Part_ID]

Output:

    Part_ID var_1 Trial var_new
 1:       1     0     1       0
 2:       1     0     2       0
 3:       2     0     1       0
 4:       3     1     1       0
 5:       4     0     1       0
 6:       5     0     1       0
 7:       5     1     2       1
 8:       6     0     1       0
 9:       6     1     2       1
10:       7     0     1       0
11:       7     0     2       0
12:       8     0     1       0
13:       8     1     2       1
14:       9     1     1       0
15:      10     0     2       0
  • Related