Issue
I'm trying to loop through columns 10 - 12 of the following data set df2, replacing 1 with a.2. with b. 3 with c and 4 with d
I've figured out how to perform the substitution on a single column using the code below.
df2[df2$DX == 1,]$DX <-'a'
df2[df2$DX == 2,]$DX <-'b'
df2[df2$DX == 3,]$DX <- 'c'
df2[df2$DX == 4,]$DX <- 'd'
df2$DX <- as.factor(df2$DX)
I'm not sure how to set up the for loop to loop over the other two columns. Thank you for your help.
Solution
Here is a tidy solution for mutating across several columns. This solution converts the four numbers to letters and converts any remaining rows to characters prior to factorizing.
library(dplyr)
mutate(df2, across(c(col10, col11, col12), ~factor(case_when(
. == 1 ~ "a",
. == 2 ~ "b",
. == 3 ~ "c",
. == 4 ~ "d",
TRUE ~ as.character(.)
))))
Answered By - dcsuka Answer Checked By - Willingham (sql.easybugfix Volunteer)
Post a Comment
Post a Comment