简体   繁体   中英

R: ifelse statement to assign a value to another column

Based on three conditions I want to assign the value 1. The following code works if I use only one & (so for example leave out 2018).

df[df$2017 == 1 & 
   df$2018 == 0 &
   df$x == -1, ]$y <- 1

I believe an ifelse statements is what I need, but I don't understand how to assign value 1 to column y within the statement.

Help is much appreciated

It is better to subset the 'y' with the logical vector instead of subsettng the whole dataset and then extracting the column

df$y[with(df, `2017` == 1 & 
                  `2018` == 0 &
                    x == -1)] <- 1

If we need to use multiple values, change the == to %in%

df$y[with(df, `2017` == 1 & 
                  `2018` == 0 &
                    x == -1 &
                  `2019` %in% c(0, 1))] <- 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM