ITPub博客

首页 > > > 【R语言】tidyverse之四:选择列

【R语言】tidyverse之四:选择列

作者:浪花小雨滴 时间:2020-06-17 10:47:39 0 删除 编辑

用 dplyr 包中的 select() 对数据框做选择列、排序列、重命名列。

一. 用列名选择列

starwars %>%
  select(name, height, mass) 

可以用“:”选择连续的若干列:

starwars %>%
  select(name:mass)   # 结果同上

tidyverse 包提供了一些助手函数,帮助选择变量,常用的有:

更多信息查看 ?tidyselect::select_helpers.

iris <- iris %>% as_tibble() 

iris %>%
  select(starts_with("Petal"))
iris %>%
  select(ends_with("Length"))
iris %>%
  select(contains("."))

根据正则表达式匹配选择列:

msleep %>%
  select(matches("o.+er"))

二. 根据条件选择列

用 select_if() 可以根据条件(逻辑判断)选择列,例如选择所有数值型的列:

starwars %>%
  select_if(is.numeric)

也可以使用,能够检验某条件并返回 TURE 或 FALSE 的自定义函数:

less_than_500 <- function(x) {
  sum(x) < 500
}

iris[1:4] %>%
  select_if(less_than_500)

实现上述选择,更简单的做法是用“~”表示的匿名函数:

iris[1:4] %>%
  select_if(~ sum(.) < 500)   # 结果同上

结合 n_distinct() 选择唯一值数目满足某条件的列:

msleep %>%
  select_if(~n_distinct(.) < 10)

三. 对列排序

列是根据被选择的顺序排列。

iris %>%
  select(ends_with("Length"), Species, ends_with("Width"))

everything() 选择器返回未被选择的所有列,这在对数据框的列做排序时很有用:

iris %>%
  select(Species, everything())

四. 删除列

用“-”删除列。

iris %>%
  select(-Species, -Petal.Length)
iris %>%
  select(-ends_with("Length"))
iris %>%   
  select(Species, everything(), -ends_with("Length"))

注意: -ends_with(...) 要放在 everything() 后面,否则删除的列就全回来了。

五. 重命名列

iris %>%
  set_names("sep_len", "sep_wid", "pet_len", "pet_wid", "spp") %>%
  names()
iris %>%
  rename(sep_len=Sepal.Length, sep_wid=Sepal.Width) %>%
  names()

注:也可以用 janitor 包中的 clean_names() 自动修正列名。


参考文献:

  1. Desi Quintans, Jeff Powell. Working in the Tidyverse. hiercourse.com/
  2. Garrett Grolemund, Hadley Wickham. R for Data Science. r4ds.had.co.nz/


————————————————

转载请注明,禁止用于出版。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3149693/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-05-16

  • 博文量
    4259
  • 访问量
    39991