'function to check or validating response in two columns

I want a function which can validate text in two column like and on the basis of two column it can create a new data frame with columns.

Criteria: for example in below sample data frame i am asking two question if first question answer is Yes then i need to validate there should be response in second column also for response Yes in first column.

Then i need to create a new data frame which confirms the above criteria follows. function is required so that i can apply that to many questions.

going forward i will create a summary tables with all the new columns.

df <- data.frame("have mobile" = c("Yes",   "No",   "No",   "No",   "No",   "Yes",  "No",   "Yes",  "Yes",  "No",   "No",   "No",   "Yes"),
                 "Which model" = c("c1",    NA, NA, NA, NA, "c2",   NA, "c2",   "c3",   NA, NA, NA, "c3"))


func1 <- function(df,col_1,col_var_1,col2,col_var2){
  
  df[new_col1] <- ifelse(df[col_1]==col_var_1,df[col2]==is.na(df[col2]),"should be ok","")
 
  df 
}

enter image description here

r


Solution 1:[1]

The function below only creates the new vector, it doesn't create it as a new column. This is because the data.frame will have to be reassigned in the global environment anyhow and to change a data.frame is less computationally efficient.

df <- data.frame("have mobile" = c("Yes",   "No",   "No",   "No",   "No",   "Yes",  "No",   "Yes",  "Yes",  "No",   "No",   "No",   "Yes"),
                 "Which model" = c("c1",    NA, NA, NA, NA, "c2",   NA, "c2",   "c3",   NA, NA, NA, "c3"))


func1 <- function(x, col_1, col_var_1 = "Yes", col_2, new_col_value = "should be OK"){
  i <- x[[col_1]] == col_var_1
  j <- is.na(x[[col_2]])
  new <- rep(NA_character_, nrow(x))
  new[i & !j] <- new_col_value
  new
}

df$new_col <- func1(df, col_1 = 1, col_2 = 2)
df
#>    have.mobile Which.model      new_col
#> 1          Yes          c1 should be OK
#> 2           No        <NA>         <NA>
#> 3           No        <NA>         <NA>
#> 4           No        <NA>         <NA>
#> 5           No        <NA>         <NA>
#> 6          Yes          c2 should be OK
#> 7           No        <NA>         <NA>
#> 8          Yes          c2 should be OK
#> 9          Yes          c3 should be OK
#> 10          No        <NA>         <NA>
#> 11          No        <NA>         <NA>
#> 12          No        <NA>         <NA>
#> 13         Yes          c3 should be OK

Created on 2022-04-17 by the reprex package (v2.0.1)

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 Rui Barradas