How to create a column in R under specific conditions?

Asked

Viewed 1,618 times

1

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 lines with y=2, w=4 and z<25 & z>15, and value 0 for any other features?

1 answer

6


Just make a logical condition composed of the various elementary conditions of the question.

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

Like the logical values FALSE/TRUE in Rare coded as 0/1, we use the function as.integer to change class. Two other ways would be to add 0L (integer zero) or multiply by 1L (a whole). But these two ways although they are widely used are barely readable and are actually "hacks". They force the Rto treat logical values as integers so that arithmetic operations can be performed.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.