-1

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.

yindalon
  • 267
  • 3
  • 12

2 Answers2

1

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.

Frank
  • 66,179
  • 8
  • 96
  • 180
1

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
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • 1
    followup question. how would I use the same varname for the renamed column. i.e. something like. mpg %>% mutate_(varname=interp(~replace(varname>25, 1 ,0), varname=as.name(varname))) – yindalon Aug 25 '15 at 00:50
  • that would be an excellent follow-up (read: additional, new) question! – hrbrmstr Aug 25 '15 at 00:51
  • posted a followup at http://stackoverflow.com/questions/32194070/creating-a-column-with-replaced-values-using-mutate-and-dplyr. thanks. – yindalon Aug 25 '15 at 01:13