dplyr mutate替换动态变量名 [英] dplyr mutate replace dynamic variable name

查看:369
本文介绍了dplyr mutate替换动态变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将hwy> 25的值替换为0,否则为0。

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))

如何用hwy替换为变量名。以下行:

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.

推荐答案

也可以将评论变成答案(并使您的问题重现):

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

这篇关于dplyr mutate替换动态变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆