1
votes

The following code replaces the values of hwy > 25 with 1 otherwise 0.

library(ggplot2)
data(mpg)
mpg %>% mutate(hwybin=replace(hwy>25,1,0))

How would I do the replace with hwy as a variable name. Something along the lines of:

varname <- "hwy"
mpg %>% mutate(hwybin=replace(varname>25,1,0))

I feel like I'm missing something obvious. Thank you.

2
ah yes, you are correct. The data is part of the ggplot2 package. - yindalon
So, what exactly are you trying to do here? Are you trying to create the name hwybin dynamically? Or substitute varname dynamically? - Rich Scriven
Okay, I undeleted my answer. I think it's what you want - Rich Scriven
mpg %>% mutate_(hwybin=interp(~replace(varname>25, 1 ,0), varname = as.name(varname))) ought to do it - hrbrmstr
thanks. this is the answer I was looking for. could you add as an answer. - yindalon

2 Answers

1
votes

Might as well turn the comment into an answer (and make your question reproducible):

library(dplyr)
library(ggplot2)
library(lazyeval)

data(mpg)

a <- mpg %>% mutate(hwybin=replace(hwy>25, 1 ,0))

varname <- "hwy"
b <- mpg %>% mutate_(hwybin=interp(~replace(varname>25, 1 ,0),
                                   varname=as.name(varname)))

identical(a, b)
## [1] TRUE
1
votes

I would do this:

library(data.table)
mybin <- function(DF,var,thresh,suffix="bin")
  DF %>% mutate(x = + ( .[[var]] > thresh )) %>% setnames("x", paste0(var,suffix)) %>% `[`

mpg %>% mybin("hwy",25)

I'm sure there is some dplyr-flavored alternative to data.table's setnames, but I don't know of it.