mercredi 24 mars 2021

Create a new column based on a specific value appearing in a row at least once from the specific columns using R?

I have something like this

col1|col2|col3|col4|col5
  Y     Y   Y    N    N
  N     N   N    N    Y
  Y     Y   Y    N    N
  N     N   N    N    N
  N     Y   N    N    N
  N     N   N    N    N
  Y     Y   Y    Y    Y 

Once i run the script i expect my result to be

   col1|col2|col3|col4|col5|result
  Y     Y   Y    N    N       Y
  N     N   N    N    Y       Y
  Y     Y   Y    N    N       Y
  N     N   N    N    N       N
  N     Y   N    N    N       Y
  N     N   N    N    N       N
  Y     Y   Y    Y    Y       Y

I tried something like this, but it did not work

COL_LIST <- c("col1","col2","col3","col4","col5")

df$result<- apply(df, 1, function(x) ifelse(any(df[COL_LIST] == "Y"), "Y", "N"))

Aucun commentaire:

Enregistrer un commentaire