dplyr

1.syntax-Helpful conventions for wrangling

  • .tbl_df
    converts data to tbl class.tbls arre easier to examine than data frames.R displays only the data that fits onscreen
library(dplyr)
tbl_df(iris)
  • .glimpse
    Information dense summary of tbl data.
glimpse(iris)
  • .View{utils}
    View data set in spreadsheet-like display(note capital V)
View(iris)
  • .%>%
    Passes object on lefthand side as first argument(or.argument) of function on righthand side
    x %>% f(y) is the same as f(x,y)
    y %>% f(x,.,z) is the same as f(x,y,z)

"Piping" with %>% makes code more readable,e.g.

iris %>% 
  group_by(Species) %>% 
  summarise(avg=mean(Sepal.Width)) %>% 
  arrange(avg)

Tidy Data-A foundation for wrangling in R
2.Reshaping Data -Change the layout of a data set
-. Gather columns into rows
tidyr::gather(cases,"year","n",2:4)
-. Spread rows into columns
tidyr::spread(pollution,size,amount)
-. Separate one column into several.
tidyr::separate(storms,date,c("y","m","d"))
-. Unite several columns into one
tidyr::unite(data,col,...,sep)

library(dplyr)
# Combine vectors into data frame(optimized)
data_frame(a=1:3,b=4:6)
# Order rows by values  od a column(low to high)
arrange(mtcars,mpg)
#Order rows by values of a column(high to low)
arrange(mtcars,desc(mpg))
#Rename the columns of a data frame
rename(tb,y=year)

3.Subset Observations(Rows)

library(dplyr)
# Extract rows that meet logical criteria
filter(iris,Sepal.Length>7)
# Remove duplicate rows
distinct(iris)
# Randomly select fraction of rows fraction(分数)
sample_frac(iris,0.5,replace = TRUE)
# Randomly select n rows
sample_n(iris,10,replace = TRUE)
#Select rows by position.
slice(iris,10:15)
#Select and order top n entries(by group if grouped data)
#top_n(storms,2,date)

Logic in R - ?Comparison, ?base::logic
4.Subset Variables(Volumns)

library(dplyr)
#Select columns by name or helper function.
select(iris,Sepal.Width,Petal.Length,Species)
## Helper functions for select -  ?select
# Select columns whose name contains a character string.
select(iris,contains("."))
#  Select columns whose name ends with a character string.
select(iris,ends_with("Length"))
# Select every column.
select(iris,everything())
# Select columns whose name matches a regular expression
select(iris,matches(".t."))
# Select columns whose names are in a group of names
select(iris,one_of(c("Species","Genus")))
# Select columns named x1,x2,x3,x4,x5
select(iris,num_range("x",1:5))
#  Select columns whose name starts with a charactere
select(iris,starts_with("Sepal"))
# Select all columns between Sepal.Length and Petal.Width(inclusive)
select(iris,Sepal.Length:Petal.Width)
# select all columns except Species
select(iris,-Species)

5.Summarise Data

library(dplyr)
# Summarise data into single row of values
summarise(iris,avg = mean(Sepal.Length))
# Apply summary function to wach column
summarise_each(iris,funs(mean))
# Count number of rows with  each unique value of variable(with or without weights)
count(iris,Species,wt = Sepal.Length)

Summarise uses summary functions,functions that take a vector of values and return a single value,such as:
...
6.Group Data

# Group data into rows with the same value of Species.
group_by(iris,Species)
# Remove grouping information from data frame
ungroup(iris)
# Compute separate summary row for each group
iris  %>% group_by(Species) %>% summarise(...)
# Compute new variables by group
iris %>% group_by(Species) %>% mutate(...)

7.Make New Variables

library(dplyr)
# Compute and append one or more new columns.
mutate(iris,sepal=Sepal.Length+Sepal.Width)
#Apply window function to each column.
mutate_each(iris, funs(min_rank))
# Compute one or more new columns.Drop original columns
transmute(iris,sepal=Sepal.Length + Sepal.Width)

window function
Mutate uses window functions,functions that take a vector of values and return another vector of values,such as:

dplyr::lead         Copy with values shifted by 1.
       lag          Copy with values lagged by 1.
       dense_rank   Ranks with no gaps
       min_rank     Ranks.Ties get min rank
       percent_rank Ranks rescaled to [0,1]
       row_number   Ranks.Ties got to first value
       ntile        Bin vector into n buckets
       between      Are values between a and b?
       cume_dist    Cumulative distribution
       cumall       Cumulative all
       cumany       Cumulative any
       cummean      Cumulative mean
       cumsun
       cunmax
       cummin
       cumprod
       pmax         Element-wise max
       pmin         Element-wise min

8.Combine Data Set

  • .Mutating Joins
a <- data.frame(x1=c('A',"B",'C'),x2=c(1,2,3))
b <- data.frame(x1=c('A',"B",'D'),x3=c('T','F','T'))
#Join matching rows from b to a
left_join(a,b,by='x1')
# Join matching rows from a to  b
right_join(a,b,by='x1')
#Join data.Retain only rows in both  set
inner_join(a,b,by='x1')
#Join data.Retain all values,all rows.
full_join(a,b,by='x1')
  • .Filtering Joins
#Allrows in a that have a match in b
semi_join(a,b,by='x1')
# All rows in a that do not have a match in b
anti_join(a,b,by='x1')
  • .Set Operations
y <- data.frame(x1=c('A',"B",'C'),x2=c(1,2,3))
z <- data.frame(x1=c("B",'C','D'),x2=c(2,3,4))
#Rows that appear in both y and z.
intersect(y, z)
#Rows that appear in either or both y and z
union(y,z)
#Rows that appear in y but not z
setdiff(y,z)

-.Binding

#append z to y as new rows
bind_rows(y,z)
# Append z to y as new columns.Caution:matches rows by position
bind_cols(y,z)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,392评论 0 23
  • 曲在手机 耳机在心 几年不舍删除 也不常听 偶尔睡醒 明亮的屋里只我一人 我坐在床上 不知觉翻出你的照片呆了很久 ...
    双子与蛇阅读 168评论 0 0
  • 青春似梦,昙花一现,仿若所有的美好和幸运都在那一刻用尽,有限的幸福总是值得令人期待。 兜兜转转,我们都回到了原点,...
    沐心曼阅读 784评论 0 4
  • 有时候,处理事情的过程中脑子里的想法就像山峰一样冒了出来,孔雀性格的人当然要表述一番自己的点子。刚刚激发出一点光芒...
    单反爱运动阅读 134评论 0 0
  • 今天,我们一起去“外滩玺园。”哥哥骑着一辆自行车,我坐在电动车后面,我们玩的很开心。我认识了很多朋友。我们玩了滑梯...
    16小石头艺谋阅读 118评论 0 1