Reputation: 297
This likely a duplicate somewhere on stackoverflow and is a followup question to dplyr mutate replace dynamic variable name.
Now I am trying to use a variable name as the new column.
Something like:
library(ggplot2)
data(mpg)
mpg %>% mutate(hwy=replace(hwy, hwy>29,10))
The code below creates a new column called varname but I want to replace the column with 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 this doesn't work. I think the dots notation is in play but not quite sure how to wrap my head around it.
Thank you.
Upvotes: 0
Views: 2320
Reputation: 78792
Rather than replace mpg
's existing hwy
variable I did the following to illustrate the same thing and put it into context:
From your previous question:
library(dplyr)
library(ggplot2)
library(lazyeval)
data(mpg)
# "normal" dplyr
a <- mpg %>% mutate(hwybin=replace(hwy>25,1,0))
# varying just the RHS
varname <- "hwy"
b <- mpg %>% mutate_(hwybin=interp(~replace(varname>25, 1 ,0),
varname=as.name(varname)))
identical(a, b)
For this particular question:
# varying both RHS and 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)
Upvotes: 1