R成精-用dplyr高效变换数据和处理数据

2017-12-16  本文已影响60人  果果哥哥BBQ

dplyr包介绍

dplyr包是R大神大杰作,Hadley Wickham,被称为一个改变R的人,dplyr是在plyr上升级的又一力作。
dplyr包包含了数据整理、筛选、变换、汇总等多种函数。基本上可以解决数据处理的80%的问题。

基础用法

本文以自己构造的数据集进行演示,以便方便理解。

data1 <- data.frame(id=c(1:10),class=c(1:2),score=c("十","九","八","七","六","五","四","三","二","一")
ennum=c("one","two","three","four","five","ten","nine","eight","seven","six"),type=c("a","b"))
data2 <- rbind(data1,c(10,6,"一","six","b"))


  1. 单表操作
data1 %>% arrange()
data1 %>% arrange(desc(id))
data1 %>% arrange(by=class)
data2 %>% distinct()
data2 %>% distinct(type)
 type
1    a
2    b
data2 %>% distinct(type,.keep_all=TRUE)
id class score ennum type
1  1    15    十   one    a
2  2    14    九   two    b
==, >, >= etc

&, |, !, xor()

is.na()

between(), near()
data2 %>%filter(id==10)
id class score ennum type
1 10     6    一   six    b
2 10     6    一   six    b

等价于

data2[id==10,]
data1 %>% group_by(class) #按照class进行分组,在组内可以进行统计操作。

# A tibble: 10 x 5
# Groups:   class [2]
      id class  score  ennum   type
   <int> <dbl> <fctr> <fctr> <fctr>
 1     1     1     十    one      a
 2     2     2     九    two      b
 3     3     1     八  three      a
 4     4     2     七   four      b
 5     5     1     六   five      a
 6     6     2     五    ten      b
 7     7     1     四   nine      a
 8     8     2     三  eight      b
 9     9     1     二  seven      a
10    10     2     一    six      b

ungroup

  1. 两个表操作
  1. 向量函数
    between
    介于两向量之间
    case_when

coalesce
cumull cumany cumean
desc降序排列
if_else
lead lag
向前和滞后
order_by
排序

n
观测值的数量
n_distinct
不同的观测值的数量
na_if
near
比较两组向量是否相等,等价于"=="
nth first last
向量中第n、第一、最后一个元素
row_number ntitle
min_rank dense_rank
percent_rank cum_dist
recode recode_factor

  1. 元数据
    groups
    分组

groups_vars

  1. 数据集
    dplyr 包中包含乐队成员信息,NASA的空间数据,星际争霸人物特征,和风暴数据:
    band_instruments、band_instruments2 、band_members 、nasa 、starwars、storms

扩展用法

参考

官方参考

上一篇 下一篇

猜你喜欢

热点阅读