'functionality to compare the database

I am trying to create a function which can do some test over the database. its something i am creating new to my code.

for example i have a database of survey in which we are getting response so first question(DD1) is like do you have a mobile and 1 = Yes , 2 = no, then question(DD2) is do you have android phone then answer should be yes or no.

case 1 : if dd1 have 1 then there should be answer in dd2 if this fulfill then column (TT2) in new data frame be like "should be ok"

case 2 : if dd1 have 2 then there should not be any response in dd2 if this is true the tt2 is blank but if it is false then tt2 be "cant be ok check the data" .

case 3 : if dd1 and dd2 have no response then tt2 be " can be ok "

df <- data.frame(`id` = c("se201",  "se202",    "se203",    "se204",    "se205",    "se206",    "se207",    "se208",    "se209"),
                 `DD1` = c(2,   1,  2,  1,  1,  1,  2,  2,  1),
                 `DD2` = c(NA,  "Yes",NA,   "Yes",  "Yes",  NA, "No",   NA, "Yes"),
                 `DD3` = c("Old",   "New",  "Old",  "New",  "Old",  "Old",  "New",  "New",  "Old"))


# mutate(df,
#        new_col = if_else(condition = have.mobile == "Yes" & !is.na(Which.model),
#                          true = "should be ok",
#                          false = NULL
#        )

the out is required like

enter image description here

r


Solution 1:[1]

Try this dplyr::case_when attempt:

library(dplyr)
df %>%
  mutate(
    TT2 = case_when(
      DD1 == 1 & !is.na(DD2) ~ "should be ok",
      DD1 == 2 & is.na(DD2) ~ "",
      DD1 == 2 & !is.na(DD2) ~ "cant be ok check the data",
      is.na(DD1) & is.na(DD2) ~ "can be ok"
    )
  )
#      id DD1  DD2 DD3                       TT2
# 1 se201   2 <NA> Old                          
# 2 se202   1  Yes New              should be ok
# 3 se203   2 <NA> Old                          
# 4 se204   1  Yes New              should be ok
# 5 se205   1  Yes Old              should be ok
# 6 se206   1 <NA> Old                      <NA>
# 7 se207   2   No New cant be ok check the data
# 8 se208   2 <NA> New                          
# 9 se209   1  Yes Old              should be ok

Your logic is missing at least one condition (seen in row 6) unless I misinterpreted your three bullets. Regardless, I think your way-forward can use this as a good start.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1