mercredi 21 juillet 2021

Generating different class vectors with one function

DV<-DV %>%
      mutate(outcome_diff=case_when(
  is.numeric(outcome) ~ outcome1-outcome2
  is.factor(outcome) ~ ifelse(outcome1==outcome2,"agree","disagree"), 
  IV$outcome==NA|IV$outcome2==NA ~NA_character_,  
  TRUE ~ NA_character_)) 

In the previous code, we successed to make a loop to generatate many outcomes. for each outcome, we generate outcome1 and outcome2.

In the presented code, What I tried to do was

  1. if the outcome variable is numeric, generate outcome_diff variable by (outcome1-outcome2)
  2. if the outcome variables is factors, do this: (ifelse(outcome1==outcome2, "agree","disagree").

However, I faced a problem that NA_character_ generates errors. Moreover, I guess case_When() function does not like to deal with different class vectors.

is there any better way to do this?

Thanks.

Aucun commentaire:

Enregistrer un commentaire