How to create a column in R under specific conditions?

0

Consider the following data.frame:

data <- data.frame(x=c("a","b","c","d"), y=c(2,2,1,2),w=c(4,4,2,2),z=c(25,16,24,30), k=c("sim","nao","sim","nao"))

How to include a new column where we will have value 1 for the lines with y = 2, w = 4 and z 15, and value 0 for any other characteristics?

    
asked by anonymous 14.11.2017 / 23:14

1 answer

6

Just do a logical condition made up of the various elementary conditions of the question.

data$novaCol <-  with(data, as.integer(y == 2 & w == 4 & 15 < z & z < 25))

Since the logical values FALSE/TRUE in R are encoded as 0/1 , we use the as.integer function to change the class. Another two ways would be to add 0L (zero integer) or multiply by 1L (an integer). But these two ways, despite being widely used, are barely legible and are actually hacks. They force R to treat logical values as integers in order to perform arithmetic operations.

with(data, (y == 2 & w == 4 & 15 < z & z < 25) + 0L)
with(data, (y == 2 & w == 4 & 15 < z & z < 25) * 1L)
    
14.11.2017 / 23:25