Creating New Variables with Multiple Conditions

Hi everyone,

I'm still in the learning phase with R, and I'm struggling to create two different new variables based off multiple conditions of other variables:

  1. I have two continuous variables with values from two separate cognitive stressors and a counterbalancing variable (values 1, 2) to indicate the order these tasks were completed. I'd like to create a new variable for "Cognitive Stressor 1", where if value is 1 in the counterbalance variable, I'd like it to insert the value from one of the continuous task variables, and if "2" to insert the value from the other. I'm not finding any example code that points me in the right direction for these from the resources I usually use.

  2. I'm trying to create a continuous variable based on multiple conditions from other variables in my dataset. Specifically, I tried using the "as.factor" method to indicate that if there were low scores on all five of the variables (<6) to classify as "0", if they responded low on two variables (<6) and higher scores on three others (>6) to classify as "1", and etc. in order to classify 4 different categories of responders. There are 5 different variables that will be used to create this single categorical variable. Here's an example of the code I tried to run, but it only created my first two categories:

clean_data$CTQ_Exposure <- as.factor( ifelse(clean_data$CTQ_PN < 6 & clean_data$CTQ_EN < 6 & clean_data$CTQ_PA < 6 & clean_data$CTQ_SA < 6 & clean_data$CTQ_EA < 6, '0', ifelse(clean_data$CTQ_PN > 5 || clean_data$CTQ_EN > 5 & clean_data$CTQ_PA < 6 & clean_data$CTQ_SA < 6 & clean_data$CTQ_EA < 6, '1', ifelse(clean_data$CTQ_PN < 6 & clean_data$CTQ_EN < 6 & clean_data$CTQ_PA > 5 || clean_data$CTQ_SA > 5 || clean_data$CTQ_EA > 5, '2', '3'))))

Am I on the right track using this method, or is there a better way to approach the creation of this variable?

Any feedback on either question is extremely appreciated!

See the FAQ: How to do a minimal reproducible example reprex for beginners. Some representative data will make illustrating answers easier.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.