Home > Net >  How to keep the missing values when using ifelse in R
How to keep the missing values when using ifelse in R

Time:06-09

I have a subset of data as below. I would like to make a new column to say if all the values in column x1, x2 and x3 is one, then "yes" and if it is two then "no".

structure(list(x1 = c("1", "1", "1", "2", NA, "2", "2", NA,NA, "1", "1", "1"), 
           x2 = c(NA, NA, "1", NA, "2", NA, "2", "2", "1", "1", "1", "1"), 
           x3 = c(NA, NA, "1", NA, "2", NA,"1", "1", "2", "1", "2", "1")), 
           class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L))

I tried below, but it is not correct. I appreciate your help.

d$new <- ifelse(!is.na(d$x1 ==1 & d$x2 ==1 d$x3 ==1 ), "yes","no")

CodePudding user response:

You can try to do this by using case_when expression from tidyverse. You need to start by activating tidyverse library:

library(tidyverse)

After that the code would look something like this:

df <- structure(list(x1 = c("1", "1", "1", "2", "NA", "2", "2", "NA","NA", "1", "1", "1"), 
           x2 = c(NA, NA, "1", "NA", "2", "NA", "2", "2", "1", "1", "1", "1"), 
           x3 = c(NA, NA, "1", NA, "2", "NA","1", "1", "2", "1", "2", "1")), 
      class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -12L))

df <- x |> mutate(new_col = case_when(
          x1 == 1 & x2 == 1 & x3 == 1 ~ "Yes",
          TRUE ~ "No"))

The mutate expression makes a new column and the case when is for doing the if else conditioning. For more clarification you can visit this link https://stringr.tidyverse.org/

CodePudding user response:

Try this

d$new <- ifelse(d$x1 ==1 & d$x2 ==1 & d$x3 ==1 , "yes",
               ifelse(d$x1 ==2 & d$x2 ==2 & d$x3 ==2 , "no", NA))
  • Related