I have some code that calculates quantiles and saves it under a new variable. Now I am trying to modify the code so I can use it in a loop. Here is a sample dataset, the original code, and the output.
df <- data.frame(country = c("Algeria", "Egypt", "Ethiopia"),
ward_1 = c(25, 75, 35),
ward_2 = c(30, 185, 60))
df %>%
mutate(
ward_1_quant = case_when(
ward_1 >= quantile(df$ward_1, 2/3) ~"High",
ward_1 >= quantile(df$ward_1, 1/3) ~"Med",
TRUE~"Low"
)
)
df <- data.frame(country = c("Algeria", "Egypt", "Ethiopia"),
ward_1 = c(25, 75, 35),
ward_2 = c(30, 185, 60),
ward_1_quant = c(Low, Med, High))
Now I want to use the value of a variable "ward_num" to specify the column. I turn that into a string called "ward_name" and try to use it in the mutate(). Here is where I got stuck:
ward_num <- 2
ward_name <- paste0("ward_",ward_num)
df %>%
mutate(
paste0(ward_name,"_quant") = case_when(
ward_name >= quantile(df[ward_name], 2/3) ~"High",
ward_name >= quantile(df[ward_name], 1/3) ~"Med",
TRUE~"Low"
)
)
r returns the error:
Error: unexpected '=' in: " mutate( paste0(ward_name,"_quant") ="
I think the issue is that I want to use the string in ward_name but the code is using ward_name literally. Any suggestions?