Hi all,
I looked for similar topics in the forum but could not find any response so apologies if this has ben covered... And apologies if the solution is simple.
So I have a simple code to recode a variable in my data frame (basically I have a 1-10 variable called "x1" and I am recoding in into a 5-point scale categorical one:
y <- c("Very low", "Low", "Average", "High", "Very high")
df <- df %>%
mutate(df, x1= ifelse(x1 %in% 1:2, y[1],
ifelse(x1 %in% 3:4,y[2],
ifelse(x1 %in% 5:6,y[3],
ifelse(x1 %in% 7:8, y[4], y[5])))))
Thus far, all works well.
However, I have other variables x1, x2 etc. and I would like to create a function to recode these variables automatically in my df. I wrote the following:
lab_lh <- function(var) {
y <- c("Very low", "Low", "Average", "High", "Very high")
df<- df%>%
mutate(var = ifelse(var %in% 1:2, y[1],
ifelse(var %in% 3:4,y[2],
ifelse(var %in% 5:6,y[3],
ifelse(var %in% 7:8, y[4], y[5])))))
}
lab_lh(df$x1) #I added the df because of the masking issues within functions and I did not manage to apply the solutions offered in other topics.
Is there a simple way to solve this?
Many thanks
Mary