使用mutate和dplyr创建一个带有替换值的列 [英] creating a column with replaced values using mutate and dplyr

查看:144
本文介绍了使用mutate和dplyr创建一个带有替换值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是stackoverflow上的一个重复,并且是 dplyr mutate替换动态的后续问题变量名称

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.

某些东西:

 library(ggplot2)
 data(mpg)
 mpg %>% mutate(hwy=replace(hwy, hwy>29,10))

以下代码创建一个新列称为varname,但是我想用hwy替换列。

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

如下所示:

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.

谢谢。

推荐答案

而不是替换 mpg 现有的 hwy 变量以下说明相同的事情,并将其放入上下文中

Rather than replace mpg's existing hwy variable I did the following to illustrate the same thing and put it into context:

从您以前的问题:

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)

对于此特定r问题:

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

这篇关于使用mutate和dplyr创建一个带有替换值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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