【发布时间】:2021-07-24 14:14:57
【问题描述】:
这与question 有某种关联:
原则上,我尝试了解rowwise 与mutate 在多个列中应用超过1 个函数(如(mean()、sum()、min() 等)的工作原理。
我了解到 across 完成这项工作,而不是 c_across。
我了解到函数 mean() 与函数 min() 不同,因为 mean() 不适用于数据帧,我们需要将其更改为可以使用 unlist 或 as.matrix 完成的向量 ->向罗纳克·沙阿学习hereUnderstanding rowwise() and c_across()
现在以我的实际情况为例:我能够完成这项任务,但我丢失了一列 d。在此设置中如何避免d 列松动。
我的 df:
df <- structure(list(a = 1:5, b = 6:10, c = 11:15, d = c("a", "b",
"c", "d", "e"), e = 1:5), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
无效:
df %>%
rowwise() %>%
mutate(across(a:e),
avg = mean(unlist(cur_data()), na.rm = TRUE),
min = min(unlist(cur_data()), na.rm = TRUE),
max = max(unlist(cur_data()), na.rm = TRUE)
)
# Output:
a b c d e avg min max
<int> <int> <int> <chr> <int> <dbl> <chr> <chr>
1 1 6 11 a 1 NA 1 a
2 2 7 12 b 2 NA 12 b
3 3 8 13 c 3 NA 13 c
4 4 9 14 d 4 NA 14 d
5 5 10 15 e 5 NA 10 e
工作,但我失去了专栏d:
df %>%
select(-d) %>%
rowwise() %>%
mutate(across(a:e),
avg = mean(unlist(cur_data()), na.rm = TRUE),
min = min(unlist(cur_data()), na.rm = TRUE),
max = max(unlist(cur_data()), na.rm = TRUE)
)
a b c e avg min max
<int> <int> <int> <int> <dbl> <dbl> <dbl>
1 1 6 11 1 4.75 1 11
2 2 7 12 2 5.75 2 12
3 3 8 13 3 6.75 3 13
4 4 9 14 4 7.75 4 14
5 5 10 15 5 8.75 5 15
【问题讨论】: