99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀R語言dplyr包學(xué)習(xí)筆記(詳細(xì)版)
R語言dplyr包學(xué)習(xí)筆記(詳細(xì)版)
2020-05-07
收藏

R語言dplyr包主要用于數(shù)據(jù)清洗和整理,主要功能有:行選擇、列選擇、統(tǒng)計匯總、窗口函數(shù)、數(shù)據(jù)框交集等是非常高效、友好的數(shù)據(jù)處理包,學(xué)清楚了,基本上數(shù)據(jù)能隨意玩弄,對的,隨意玩弄,簡直大大提高數(shù)據(jù)處理及分析效率。我以為,該包是數(shù)據(jù)分析必學(xué)包之一。學(xué)習(xí)過程需要大量試驗,領(lǐng)悟其中設(shè)計的精妙之處。


          作者:小伍哥

          來源:AI入門學(xué)習(xí)


#包安裝與加載

install.packages("dplyr")

library(dplyr)

#調(diào)用mtcars數(shù)據(jù)&數(shù)據(jù)集介紹

data(mtcars)

str(mtcars)

本文案例使用數(shù)據(jù)集 mtcars 具體結(jié)構(gòu)如下,直接加載即可共11個字段,32條數(shù)據(jù),每個字段的含義如下:mpg-百公里油耗;cyl-氣缸數(shù);disp-排量;hp-馬力;drat-軸距;wt-重量; qsec-百公里時間 ;vs-發(fā)動機(jī)類型

##############################################################

按行篩選: filter()

按給定的邏輯判斷篩選出符合要求的子數(shù)據(jù)集, 類似于 subset() 函數(shù)

filter(mtcars, mpg>=22)

filter(mtcars, cyl == 4 | gear == 3)

filter(mtcars, cyl == 4 & gear == 3)

注意: 表示 AND 時要使用 & 而避免 &&

##############################################################

按列篩選:select 

select()用列名作參數(shù)來選擇子數(shù)據(jù)集。dplyr包中提供了些特殊功能的函數(shù)與select函數(shù)結(jié)合使用,用于篩選變量,包括starts_with,ends_with,contains,matches,one_of,num_range和everything等。用于重命名時,select()只保留參數(shù)中給定的列,rename()保留所有的列,只對給定的列重新命名。原數(shù)據(jù)集行名稱會被過濾掉。

data(iris)

iris = tbl_df(iris)  

#選取變量名前綴包含Petal的列  

select(iris, starts_with("Petal"))  

#選取變量名前綴不包含Petal的列  

select(iris, -starts_with("Petal"))  

#選取變量名后綴包含Width的列  

select(iris, ends_with("Width"))  

#選取變量名后綴不包含Width的列  

select(iris, -ends_with("Width"))  

#選取變量名中包含etal的列  

select(iris, contains("etal"))  

#選取變量名中不包含etal的列  

select(iris, -contains("etal"))  

#正則表達(dá)式匹配,返回變量名中包含t的列  

select(iris, matches(".t."))  

#正則表達(dá)式匹配,返回變量名中不包含t的列  

select(iris, -matches(".t."))  

#直接選取列  

select(iris, Petal.Length, Petal.Width)  

#返回除Petal.Length和Petal.Width之外的所有列  

select(iris, -Petal.Length, -Petal.Width)  

#使用冒號連接列名,選擇多個列  

select(iris, Sepal.Length:Petal.Width)  

#選擇字符向量中的列,select中不能直接使用字符向量篩選,需要使用one_of函數(shù)  

vars <- c("Petal.Length", "Petal.Width")  

select(iris, one_of(vars))  

#返回指定字符向量之外的列  

select(iris, -one_of(vars))  

#返回所有列,一般調(diào)整數(shù)據(jù)集中變量順序時使用  

select(iris, everything())  

#調(diào)整列順序,把Species列放到最前面  

select(iris, Species, everything())  

##############################################################

神奇變形函數(shù):mutate()transmute()

mutate()和transmute()函數(shù)對已有列進(jìn)行數(shù)據(jù)運(yùn)算并添加為新列,類似于transform() 函數(shù),不同的是可以在同一語句中對剛增添加的列進(jìn)行操作,mutate()返回的結(jié)果集會保留原有變量,transmute()只返回擴(kuò)展的新變量,原數(shù)據(jù)集行名稱會被過濾掉

1、mutate變量變形

1.1 單個變量操作:mutate可以對數(shù)據(jù)框中已有的變量進(jìn)行操作或者增加變量,值得稱贊的是,一段mutate的代碼中,靠后的變量操作可以操作前期新添加或改變的變量,這是transform所不具備的特性。

1.1.1新增列

mtcars%>% mutate(cyl2 = cyl * 2,cyl4 = cyl2 * 2)




1.1.2刪除列

mtcars %>% mutate(mpg = NULL,disp = disp * 0.0163871)

mtcars %>% mutate(cyl = NULL)

不需要的列不在了

1.1.3窗口函數(shù)應(yīng)用

mtcars %>% group_by(cyl) %>% mutate(rank    = min_rank(desc(mpg)))

mtcars %>% group_by(cyl) %>% mutate(mpg_max = max(mpg))

原來的明細(xì)還保留,同時每個分組的統(tǒng)計值算出來了,是不是很方便

1.2 批量操作

同時若你嫌麻煩一個個地對變量進(jìn)行操作,還可以使用mutate_each函數(shù)對數(shù)據(jù)框中的變量批量操作,通過調(diào)整funs(即functions)和vars(variables)參數(shù)控制functions的數(shù)量,以及參與變形的variables,這里控制variables的技巧與select函數(shù)相似。

#對每個變量進(jìn)行排名

mtcars%>%mutate_each(funs(dense_rank)) 

 mpg cyl disp hp drat wt qsec vs am gear carb

1   16   2   13 11   16  9     6   1   2   2    4

2   16   2   13 11   16 12   10  1  2    2    4

3   19   1    6  6    15  7     22  2  2    2    1

4   17   2   16 11    5 16    24  2  1    1    1

5   13   3   23 15    6 18   10   1  1    1    2

#對disp的變量進(jìn)行排名

mtcars%>%mutate_each(funs(dense_rank,min_rank),disp)

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb dense_rank min_rank

1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4         13       13

2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4         13       13

3  22.8   4 108.0  93 3.85 2.320 18.61  1   1    4    1          6          6

4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1         16       18

5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2         23       27

6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1         15       17

7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4         23        27

#對除了disp的變量進(jìn)行排名

mtcars%>%mutate_each(funs(dense_rank,min_rank),-disp)

2、transmute

返回值中不包含原數(shù)據(jù)集變量,只保留計算轉(zhuǎn)換后的變量。

mtcars%>%mutate(wt_log=log(wt))

mtcars%>%transmute(wt_log=log(wt))

mtcars %>%mutate(displ_l = disp / 61.0237)

mtcars %>%transmute(displ_l = disp / 61.0237)

##############################################################

 排名函數(shù) :ranking

row_number   通用排名,并列的名次結(jié)果按先后順序不一樣,靠前出現(xiàn)的元素排名在前

min_rank       通用排名,并列的名次結(jié)果一樣,占用下一名次。

dense_rank   中國式排名,并列排名不占用名次,如:無論有幾個并列第2名,之后的排名仍應(yīng)該是第3名

percent_rank 按百分比的排名

cume_dist    累計分布區(qū)間的排名

ntile              粗略地把向量按堆排名,n即是堆的數(shù)量

x = c(5, 1, 3, 2, 2, NA)

row_number(x)

min_rank(x)

dense_rank(x)

percent_rank(x)

cume_dist(x)

ntile(x, 2)

mtcars%>%mutate(dense_rank=cume_dist(cyl))

##############################################################

排序函數(shù): arrange()  

注意,排序與排名的區(qū)別,結(jié)合rank函數(shù)理解

按給定的列名依次對行進(jìn)行排序.

arrange(mtcars, mpg)

arrange(mtcars, mpg,disp)

對列名加 desc() 進(jìn)行倒序 或者負(fù)數(shù):

arrange(mtcars, desc(mpg))

arrange(mtcars, -mpg)

##############################################################

去重函數(shù):distinct 

distinct()用于對輸入的tbl進(jìn)行去重,返回?zé)o重復(fù)的行,類似于 base::unique() 函數(shù),但是處理速度更快。原數(shù)據(jù)集行名稱會被過濾掉。

#

df <- data.frame(  x = sample(10, 100, rep = TRUE),  

                            y = sample(10, 100, rep = TRUE)  )  

#以全部兩個變量去重,返回去重后的行數(shù)  

nrow(distinct(df))  

nrow(distinct(df, x, y))  

#以變量x去重,只返回去重后的x值  

distinct(df, x)  

#以變量y去重,只返回去重后的y值  

distinct(df, y)  

#以變量x去重,返回所有變量  

distinct(df, x, .keep_all = TRUE)  

#以變量y去重,返回所有變量  

distinct(df, y, .keep_all = TRUE)  

#對變量運(yùn)算后的結(jié)果去重  

distinct(df, diff = abs(x - y))

##############################################################

匯總函數(shù):summarise 

1、直接匯總

#返回數(shù)據(jù)框中變量disp的均值  

summarise(mtcars, mean(disp))  

#返回數(shù)據(jù)框中變量disp的標(biāo)準(zhǔn)差  

summarise(mtcars, sd(disp))  

#返回數(shù)據(jù)框中變量disp的最大值及最小值  

summarise(mtcars, max(disp), min(disp))  

#返回數(shù)據(jù)框mtcars的行數(shù)  

summarise(mtcars, n())  

#返回unique的gear數(shù)  

summarise(mtcars, n_distinct(gear))  

#返回disp的第一個值  

summarise(mtcars, first(disp))  

#返回disp的最后個值  

summarise(mtcars, last(disp))  

2、分組統(tǒng)計

# 按變量cyl分組,求disp的均值和個數(shù)

mtcars %>%group_by(cyl) %>%

summarise(mean = mean(disp), n = n())

# 按變量cyl, vs分組,求每個組的記錄數(shù)

mtcars %>%

group_by(cyl, vs) %>%

summarise(cyl_n = n()) %>%

group_vars()

# 按變量cyl分組,求disp的均值和標(biāo)準(zhǔn)差

mtcars %>%

group_by(cyl) %>%

summarise(disp = mean(disp), sd = sd(disp))

##############################################################

數(shù)據(jù)匹配函數(shù):join 系列

#數(shù)據(jù)框中經(jīng)常需要將多個表進(jìn)行連接操作, 如左連接、右連接、內(nèi)連接等,dplyr包也提供了數(shù)據(jù)集的連接操作,

#類似于 base::merge() 函數(shù)。語法如下: 

#內(nèi)連接,合并數(shù)據(jù)僅保留匹配的記錄

inner_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...) 

#左連接,向數(shù)據(jù)集x中加入匹配的數(shù)據(jù)集y記錄

left_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)

#右連接,向數(shù)據(jù)集y中加入匹配的數(shù)據(jù)集x記錄

right_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...) 

#全連接,合并數(shù)據(jù)保留所有記錄,所有行

full_join(x,y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), ...)

#返回能夠與y表匹配的x表所有記錄 

semi_join(x,y, by = NULL, copy = FALSE, ...)

#返回?zé)o法與y表匹配的x表的所有記錄

anti_join(x, y, by = NULL, copy = FALSE, ...) 

df1 = data.frame(CustomerId=c(1:6), sex = c("f", "m", "f", "f", "m", "m"), Product=c(rep("Toaster",3), rep("Radio",3)))  

df2 = data.frame(CustomerId=c(2,4,6,7),sex = c( "m", "f", "m", "f"), State=c(rep("Alabama",3), rep("Ohio",1)))  

#內(nèi)連接,默認(rèn)使用"CustomerId"和"sex"連接  

inner_join(df1, df2)  

#左連接,默認(rèn)使用"CustomerId"和"sex"連接  

left_join(df1, df2)  

#右連接,默認(rèn)使用"CustomerId"和"sex"連接  

right_join(df1, df2)  

#全連接,默認(rèn)使用"CustomerId"和"sex"連接  

full_join(df1, df2)  

#內(nèi)連接,使用"CustomerId"連接,同名字段sex會自動添加后綴  

inner_join(df1, df2, by = c("CustomerId" = "CustomerId"))  

#以CustomerId連接,返回df1中與df2匹配的記錄  

semi_join(df1, df2, by = c("CustomerId" = "CustomerId"))  

#以CustomerId和sex連接,返回df1中與df2不匹配的記錄  

anti_join(df1, df2)  

##############################################################

集合操作函數(shù): set

dplyr也提供了集合操作函數(shù),實際上是對base包中的集合操作的重寫,但是對數(shù)據(jù)框和其它表格形式的數(shù)據(jù)操作更加高效。語法如下:

#取兩個集合的交集

intersect(x,y, ...)

#取兩個集合的并集,并進(jìn)行去重

union(x,y, ...)

#取兩個集合的并集,不去重

union_all(x,y, ...)

#取兩個集合的差集

setdiff(x,y, ...)

#判斷兩個集合是否相等

setequal(x, y, ...)

mtcars$model <- rownames(mtcars)  

first <- mtcars[1:20, ]  

second <- mtcars[10:32, ]  

#取兩個集合的交集  

intersect(first, second)  

#取兩個集合的并集,并去重  

union(first, second)  

#取兩個集合的差集,返回first中存在但second中不存在的記錄  

setdiff(first, second)  

#取兩個集合的交集,返回second中存在但first中不存在的記錄  

setdiff(second, first)  

#取兩個集合的交集, 不去重  

union_all(first, second)  

#判斷兩個集合是否相等,返回TRUE  

setequal(mtcars, mtcars[32:1, ]) 

##############################################################

匯總函數(shù):tally系列

tally是一個很方便的計數(shù)函數(shù),其根據(jù)最初的調(diào)用而決定下一次調(diào)用n或者sum(n)。它還有其他的小伙伴比如count和n,都是計數(shù)家族的。

iris%>%group_by(Species)%>%tally

iris%>%group_by(Species)%>%tally

 

 

 ##############################################################

抽樣函數(shù):sample系列

此sample系列是對數(shù)據(jù)框進(jìn)行隨機(jī)抽樣,只作用于數(shù)據(jù)框和dplyr自帶的tbl等格式的數(shù)據(jù)。sample_n為按行數(shù)隨機(jī)抽樣,而sample_frac為按比例抽樣;其weight參數(shù)可以設(shè)置抽樣的權(quán)重而replace參數(shù)為有放回抽樣。

sample_n(mtcars,2,replace=TRUE)

sample_n(mtcars,2,weight=mpg/mean(mpg))

sample_frac(mtcars,0.1)

sample_frac(mtcars,0.1,weight=1/mpg)


看了這篇文章之后,大家對R語言dplyr包是不是更加了解了呢,希望為大家學(xué)習(xí)R語言助一臂之力。


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }