mercredi 1 septembre 2021

Defining element based on condition in R

Say that I have a dataframe (df) that looks like this:

stim <- c("a", "k", "y", "j", "t", "Stop", "f", "l", "b", "a", "c", "Stop")
df <- data.frame(stim)

I would like to create another column 'YesorNo' based on the value of 'stim'. My desired output is this:

stim  YesorNo
 a      yes
 k      yes
 y      yes
 j      yes
 t       No
 Stop   N/A
 f      yes
 l      yes
 b      yes
 a      yes
 c       No
 Stop   N/A
 ...    ...

I would like the value of 'YesorNo' to be N/A if stim is "stop". I can use a simple ifelse statement for that (df$YesorNo <- ifelse(df$stim=="Stop", "N/A", "yes") But I would also like the value that comes BEFORE "stop" (letters t and c in my example) to correspond to "no" instead of "yes". How would I define that?

Aucun commentaire:

Enregistrer un commentaire