0

我试图使用cross来获取某些列的平均值,并且为我使用的平均值的每一列创建新的不同列时出现问题。它工作正常吗?

    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 而不是另一列。

4

1 回答 1

1

across如果您想逐行mean取两列,不一定会看到这里的用法。

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))

你可以使用rowwisewithc_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))
于 2020-12-07T10:37:29.863 回答