mardi 1 octobre 2019

How to create a string variable on the basis of values of 4 other variables in a dataframe

I would like to find a quick way to produce a vector of strings in my dataframe on the basis of values of other vectors.

I have a dataframe like:

x <- data.frame("Trials" = 1:6, "Prem" = c(0,0,0,1,0,1), "Corr" = 
c(1,1,0,0,0,0), "Incorr" = c(0,0,0,0,1,0))

and want to produce another variable 'response_type' on the basis of values in Prem, Corr and Incorr. Now I do this with a loop, but I'm wondering if there's a quicker more elegant way

for (i in dataframe$Trials) {

if (dataframe$Prem[i]>0) {

dataframe$response_type[i] = 'premature'

} else if ( dataframe$Corr[i]>0) {

dataframe$response_type[i] = 'correct'

} else  {

dataframe$response_type[i] = 'incorrect'

}}

Aucun commentaire:

Enregistrer un commentaire