r - creating a column with replaced values using mutate and dplyr -
this duplicate somewhere on stackoverflow , followup question dplyr mutate replace dynamic variable name.
now trying use variable name new column.
something like:
library(ggplot2) data(mpg) mpg %>% mutate(hwy=replace(hwy, hwy>29,10))
the code below creates new column called varname want replace column hwy.
varname = "hwy" mpg %>% mutate_(varname=interp(~replace(varname, varname>29, 10), varname=as.name(varname)))
something like:
mpg %>% mutate_(as.name(varname)=interp(~replace(varname, varname>29, 10), varname=as.name(varname)))
but doesn't work. think dots notation in play not quite sure how wrap head around it.
thank you.
rather replace mpg
's existing hwy
variable did following illustrate same thing , put context:
from previous question:
library(dplyr) library(ggplot2) library(lazyeval) data(mpg) # "normal" dplyr <- mpg %>% mutate(hwybin=replace(hwy>25,1,0)) # varying rhs varname <- "hwy" b <- mpg %>% mutate_(hwybin=interp(~replace(varname>25, 1 ,0), varname=as.name(varname))) identical(a, b)
for particular question:
# varying both rhs , lhs colname <- "hwybin" z <- mpg %>% mutate_(.dots=setnames(list(interp(~replace(varname>25, 1 ,0), varname=as.name(varname))), colname)) # tests identical(a, z) identical(b, z)
Comments
Post a Comment