跨越 NA 值
Across with NA values
我尝试使用 across 计算某些列的平均值,但出现问题
为我使用的平均值的每一列制作新的不同列。
是否正常工作?
library(tidyverse)
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
group_by(names) %>%
mutate(two = across(starts_with("one"), .fns = mean))
在小插图中显示了这个例子:
df %>% mutate_at(vars(c(x, starts_with("y"))), mean)
# ->
df %>% mutate(across(c(x, starts_with("y")), mean, na.rm = TRUE))
我希望在每种情况下使用 NA 它都会产生 NA 而不是另一列。
如果要按行 mean
两列,不一定会在此处看到 across
的用法。
library(dplyr)
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
mutate(two = rowMeans(select(., starts_with('one')), na.rm = TRUE))
您可以将 rowwise
与 c_across
一起使用,但那样效率会降低 rowMeans
。
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
rowwise() %>%
mutate(two = mean(c_across(starts_with('one')), na.rm = TRUE))
我尝试使用 across 计算某些列的平均值,但出现问题 为我使用的平均值的每一列制作新的不同列。 是否正常工作?
library(tidyverse)
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
group_by(names) %>%
mutate(two = across(starts_with("one"), .fns = mean))
在小插图中显示了这个例子:
df %>% mutate_at(vars(c(x, starts_with("y"))), mean)
# ->
df %>% mutate(across(c(x, starts_with("y")), mean, na.rm = TRUE))
我希望在每种情况下使用 NA 它都会产生 NA 而不是另一列。
如果要按行 mean
两列,不一定会在此处看到 across
的用法。
library(dplyr)
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
mutate(two = rowMeans(select(., starts_with('one')), na.rm = TRUE))
您可以将 rowwise
与 c_across
一起使用,但那样效率会降低 rowMeans
。
cars %>%
as_tibble() %>%
add_case(speed = 11, dist = NA, .before = 1) %>%
add_column(names = str_c("a",1:51)) %>%
rename_with(.cols = -names, ~str_c("one_",.x)) %>%
rowwise() %>%
mutate(two = mean(c_across(starts_with('one')), na.rm = TRUE))