1

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)

Maria
  • 11
  • 3
  • 1
    Hello @Maria. Welcome on SO! Please consider providing us a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so that other SO users can help you in the best way. – lovalery Oct 28 '21 at 13:45
  • `var3 <- ifelse(var1 > 0 & var2 > 0 & (var2-var1) > 1, 1, 0)` will assign `1` to `var3` if the conditions are met and `0` otherwise. In this example it can be shortened to `+(var1 > 0 & var2 > 0 & (var2-var1) > 1)`, but if you have values other than `0` and `1`, the `ifelse` method is more flexible. – r2evans Oct 28 '21 at 13:53

2 Answers2

0

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))
Nicolas Ratto
  • 145
  • 1
  • 4
0

Solution using package data.table:

library(data.table)
data <- data[var1>0 & var2>0 & var2-var1>1, var3 := 1]
bt-koch
  • 59
  • 5