across and case_when

library(tidyverse)

#across将一个或多个函数应用在选择列上
iris %>% as_tibble() %>%
  mutate(mean=(rowMeans(across(starts_with('Sepal')))))

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with('Sepal'),mean))

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with('Sepal'),~mean(.x,na.rm = T)))

#避免了写多个列的麻烦
iris %>%
  group_by(Species) %>%
  summarise(mean=mean(Sepal.Length))


starwars %>%
  select(name:mass, gender, species) %>%
  mutate(
    type = case_when(
      height > 200 | mass > 200 ~ "large",
      species == "Droid"        ~ "robot",
      TRUE                      ~ "other"
    )
  )

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理