[英]dplyr mutate_at and case_when
I'd like to identify variables with starts_with() and then perform a case_when mutation. 我想用starts_with()识别变量,然后执行case_when变异。
For example, let's say I want to do the equivalent of: 例如,假设我想做相同的:
mtcars$mpg[mtcars$mpg == 21.0] <- 5; mtcars
My attempt: 我的尝试:
mtcars %>%
mutate_at(
vars(starts_with("mpg")),
funs(. = case_when(
. == 21.0 ~ 5,
TRUE ~ .
))
)
What am I doing wrong? 我究竟做错了什么? The dplyr documentation doesn't seem to have many examples of mutate_at/mutate_each ( this thread seems to have the same complaint), so I have a hard time with these functions.
dplyr文档似乎没有很多mutate_at / mutate_each的例子( 这个线程看起来有同样的抱怨),所以我很难用这些函数。 Maybe I am not looking in the right place?
也许我不是在寻找合适的地方?
I'm aware of this thread but wasn't able to find a solution in there. 我知道这个帖子但是在那里找不到解决方案。
Thanks! 谢谢!
funs
creates a list of functions, when you do funs(. = ...)
, it creates named functions with name of .
funs
创建一个函数列表,当你执行funs(. = ...)
,它会创建名为的命名函数.
, and this leads to new column(s) being generated with either the name of .
,这会导致使用名称生成新列
.
if you have only one column, or the name with suffix of .
如果您只有一列,或者后缀为的名称
.
if you have more than one column to mutate; 如果你有多个列要变异; If you need to overwrite the original column, simply leave the functions unnamed by directly passing the anonymous function to
funs
. 如果您需要覆盖原始列,只需通过直接将匿名函数传递给
funs
来保留未命名的函数。 In your case, removing . =
在你的情况下,删除
. =
. =
in funs
should work; . =
在funs
应该工作;
mtcars %>%
mutate_at(
vars(starts_with("mpg")),
funs(case_when(
. == 21.0 ~ 5,
TRUE ~ .
))
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.