Reputation: 1817
I need to be able to change iteration number in each seperated line of one dplyr code. I have prepared and example of 'by hand' approach and what I need to do in 'pseudo steps'.
library(tidyverse)
cr <-
mtcars %>%
group_by(gear) %>%
nest()
# This is 'by-hand' approach of what I would like to do - How to automate it? E.g. we do not know all values of 'carb'
cr$data[[1]] %>%
mutate(VARIABLE1 =
case_when(carb == 1 ~ hp/mpg,
TRUE ~ 0)) %>%
mutate(VARIABLE2 =
case_when(carb == 2 ~ hp/mpg,
TRUE ~ 0)) %>%
mutate(VARIABLE4 =
case_when(carb == 4 ~ hp/mpg,
TRUE ~ 0))
# This is a pseodu-idea of what I need to do. Is the any way how to change iteration number in ONE dplyr code?
vals <- cr$data[[1]] %>% pull(carb) %>% sort %>% unique()
for (i in vals) {
message(i)
cr$data[[1]] %>%
mutate(paste('VARIABLE', i, sep = '') = case_when(carb == i ~ hp/mpg, # At this line, all i shall be first element of vals
TRUE ~ 0)) %>%
mutate(paste('VARIABLE', i, sep = '') = case_when(carb == i ~ hp/mpg, # At this line, all i shall be second element of vals
TRUE ~ 0)) %>%
mutate(paste('VARIABLE', i, sep = '') = case_when(carb == i ~ hp/mpg, # At this line, all i shall be third element of vals
TRUE ~ 0))
}
is there any trick maybe using purrr
package or other solution as well?
I need to iterate over some unique values of some variable. And for each unique value create a new column in dataframe. I need to automatize this, however I am not able to do so on my own.
Upvotes: 0
Views: 92
Reputation: 6931
You can do this using sym
to convert text to symbols and !!
to evaluate within dplyr functions. See this question and this vignette for further details.
For your application, you probably want something like this:
carbs = c(1,2,4)
for(cc in carbs){
var_name = sym(paste0("VARIABLE",cc))
cr$data[[1]] = cr$data[[1]] %>%
mutate(!!var_name := case_when(carb == cc ~ hp/mpg,
TRUE ~ 0))
}
There are three key parts to this:
sym
turns the text string into a symbol variable.!!
means that a symbol is treated as an R expression:=
lets us use !!
evaluation on the left-hand-side of the equationUpvotes: 2