Home > Back-end >  How to create a new variable based on conditions of previous variables in R?
How to create a new variable based on conditions of previous variables in R?

Time:10-29

I have 2 numeric continuous variables that represent test scores (var1 and var2).

var1       var2
10.146     70.554
15.222     12.122
0          25.463
1.557      66.666
NA         8.545
26.447     NA

I want to create a third variable (var3) in R, using conditions based on var1 and var2 such as:

if var1>0 and var2>0 and var2-var1>1 then var3=1 

(I apologize if this is not the best way to ask a question but I am just beginning my programming journey)

CodePudding user response:

you must attach your variables to the data they belong to. For example:

data$var1

Then the following works:

In R base

data$var3 <- ifelse(data$var1 > 0 & data$var2 > 0 & (data$var2-data$var1) > 1, 1, 0)

In dplyr

library(dplyr)
data <- data %>% mutate(var3=if_else(var1 > 0 & 
                                     var2 > 0 & 
                                    (var2-var1) > 1, 1, 0))

CodePudding user response:

Solution using package data.table:

library(data.table)
data <- data[var1>0 & var2>0 & var2-var1>1, var3 := 1]
  •  Tags:  
  • r
  • Related