I have a data.frame with 266 columns, I am trying to create a grouping variable (dichotomized as 1 or 2) based on the responses in the columns of data. My data looks like this:
structure(list(M_Fha_Dha1_1 = c(2, 2, 1, 4, 0), M_Fha_Dha1_2 = c(5,
4, 4, 4, 1), M_Fla_Dha1_1 = c(NaN, NaN, NaN, NaN, NaN), M_Fla_Dha2_2 = c(NaN,
NaN, NaN, NaN, NaN)), row.names = c(NA, -5L), class = "data.frame")
I am trying to create myself a new dummy variable (Attract; 1 or 2) based on the responses from existing variables. Each variable has values from 1 to 5, unless the participant did not respond, in which case there is an NA. I have been trying to use dplyr to achieve this. Basically, I want to take all rows with responses to variables titled "M_Fha_Dha_1..." and assign a 1 to my Attract variable. Then, I want to take all rows with responses to variables titled "M_Fla_Dha_1..." and assign a 0 to my Attract variable. The idea is that I create a grouping variable based on which experimental group they were sorted into.
I can achieve this for a single column:
df1 <- df1 %>%
mutate(Attract = case_when(M_Fha_Dha1_1 >= 1 ~ 1))
However, I don't want to manually write another 249ish lines of code to achieve the same thing for the other columns. I want to mutate() across each relevant column (e.g., I want to be able to select the columns I mutate() over).
To do this I have tried to amend my code with the across() function but I get an error:
table <- table %>%
mutate(across(M_Fha_Dha1_1:M_Fla_Dha2_2, ~ case_when(Attract = 1 ~ 1)))
Any help would be fantastic! I'm not sure if I have made sense, I can always provide clarity.