I don't know how to cut dynamic variables into groups within a for loop.
df
is the data frame that contains clm_april
- clm_sept
variables that are double
. Also I would like to put different names for new columns.
Groups which are different for every month looks like this:
> groups_april
[1] "0" "500" "1000" "1500" "2000" "3500"
[7] "4500" "5000" "9500" "2000000"
The following does not work:
vector <- c("april", "may", "june", "july", "aug", "sept")
for (i in vector) {
varname <- paste0("clm_", i)
df <- df %>%
mutate_(.dots =
cut(list(varname),
breaks = groups[i],
include.lowest = T,
dig.lab = 10))
}
I have also tried:
for (i in vector) {
varname <- paste0("clm_", i)
df <- df %>%
mutate_(.dots = interp(~cut(list(varname),
breaks = groups[i],
include.lowest = T,
dig.lab = 10, varname=as.name(varname))))
}
R throws the following error:
Error in mutate_impl(.data, dots) :
Evaluation error: 'x' must be numeric.
Can you help me solve this problem?
EDIT:
# A tibble: 10 x 6
clm_april clm_may clm_june clm_july clm_aug clm_sept
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0 0 0 0 689 0
2 2000 0 1000 1000 1000 0
3 5000 1000 1000 1000 1500 1518
4 1000 1069 1100 1200 2019 2000
5 679 689 9000 10000 36681 2000
6 800 1000 1000 657 1815 2500