在编程中使用dplyr mutate() [英] use dplyr mutate() in programming
问题描述
我正在尝试使用mutate将列名分配给变量.
I am trying to assign a column name to a variable using mutate.
df <-data.frame(x = sample(1:100, 50), y = rnorm(50))
new <- function(name){
df%>%mutate(name = ifelse(x <50, "small", "big"))
}
我跑步时
new(name = "newVar")
它不起作用.我知道mutate_()
可以帮助您,但我正在努力将其与ifelse
一起使用.
it doesn't work. I know mutate_()
could help but I'm struggling in using it together with ifelse
.
任何帮助将不胜感激.
推荐答案
使用dplyr
0.7.1及其在NSE中的改进,您必须UQ
自变量mutate
,然后在分配时使用:=
.这里有很多有关dplyr
和NSE编程的信息: https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html
Using dplyr
0.7.1 and its advances in NSE, you have to UQ
the argument to mutate
and then use :=
when assigning. There is lots of info on programming with dplyr
and NSE here: https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html
为了避免混淆,我将函数参数的名称更改为myvar
.如果您还有更多要重新编码的类别,也可以使用dplyr
中的case_when
代替ifelse
.
I've changed the name of the function argument to myvar
to avoid confusion. You could also use case_when
from dplyr
instead of ifelse
if you have more categories to recode.
df <- data.frame(x = sample(1:100, 50), y = rnorm(50))
new <- function(myvar){
df %>% mutate(UQ(myvar) := ifelse(x < 50, "small", "big"))
}
new(myvar = "newVar")
这将返回
x y newVar
1 37 1.82669 small
2 63 -0.04333 big
3 46 0.20748 small
4 93 0.94169 big
5 83 -0.15678 big
6 14 -1.43567 small
7 61 0.35173 big
8 26 -0.71826 small
9 21 1.09237 small
10 90 1.99185 big
11 60 -1.01408 big
12 70 0.87534 big
13 55 0.85325 big
14 38 1.70972 small
15 6 0.74836 small
16 23 -0.08528 small
17 27 2.02613 small
18 76 -0.45648 big
19 97 1.20124 big
20 99 -0.34930 big
21 74 1.77341 big
22 72 -0.32862 big
23 64 -0.07994 big
24 53 -0.40116 big
25 16 -0.70226 small
26 8 0.78965 small
27 34 0.01871 small
28 24 1.95154 small
29 82 -0.70616 big
30 77 -0.40387 big
31 43 -0.88383 small
32 88 -0.21862 big
33 45 0.53409 small
34 29 -2.29234 small
35 54 1.00730 big
36 22 -0.62636 small
37 100 0.75193 big
38 52 -0.41389 big
39 36 0.19817 small
40 89 -0.49224 big
41 81 -1.51998 big
42 18 0.57047 small
43 78 -0.44445 big
44 49 -0.08845 small
45 20 0.14014 small
46 32 0.48094 small
47 1 -0.12224 small
48 66 0.48769 big
49 11 -0.49005 small
50 87 -0.25517 big
这篇关于在编程中使用dplyr mutate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!