我正在尝试将case_when
函数用于data.frame的一堆列。
这种情况不会返回mutate
中的指定列
cars %>% mutate (
km = speed * dist,
mt = km / 1000
) %>%
mutate (
.funs = case_when(
(speed < 20 ) ~ {
km = km * 2
mt = mt * 3
}
)
)
谢谢
答案 0 :(得分:2)
我们可以使用mutate_at
library(tidyverse)
cars %>%
mutate(km = speed * dist, mt = km/1000) %>%
mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
TRUE ~ .)))
如果我们需要为每个列使用单独的值进行计算,请使用map2
或pmap
out <- cars %>%
mutate(km = speed * dist, mt = km/1000) %>%
select(km, mt) %>%
map2_df(., list(2, 3), ~
case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
bind_cols(cars, .)
head(out)
# speed dist km mt
#1 4 2 16 0.024
#2 4 10 80 0.120
#3 7 4 56 0.084
#4 7 22 308 0.462
#5 8 16 256 0.384
#6 9 10 180 0.270
答案 1 :(得分:1)
发现此解决方案,但有点怪异和棘手
mutate_when <- function (data, ...) {
dots <- eval (substitute (alist(...)))
for (i in seq (1, length (dots), by = 3)) {
condition <- eval (dots [[i]], envir = data)
mutations <- eval (dots [[i + 1]], envir = data [condition, ])
data[condition, names(mutations)] <- mutations
mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
data[!condition, names(mutations)] <- mutations_else
}
data
}
cars %>%
mutate(
km = speed * dist,
mt = km/1000
) %>%
mutate_when(
speed < 20,
list (
km = km * 2,
mt = mt * 3
),
list (
0
)
)
给予
speed dist km mt
1 4 2 16 0.024
2 4 10 80 0.120
3 7 4 56 0.084
4 7 22 308 0.462
5 8 16 256 0.384
6 9 10 180 0.270