R for Data Science
想了一下還是做一個筆記目錄,這樣能夠方便查詢
R for Data Science(筆記) ---數(shù)據(jù)變換(filter使用)
R for Data Science(筆記) ---數(shù)據(jù)變換(select基礎(chǔ)使用)
R for Data Science(筆記) ---數(shù)據(jù)變換(select組合其他函數(shù))
R for Data Science(筆記) ---數(shù)據(jù)變換(創(chuàng)建新的變量)
R for Data Science(筆記) ---數(shù)據(jù)變換(行排序)
R for Data Science(筆記) ---數(shù)據(jù)變換(歸納總結(jié))
R for Data Science(筆記) ---數(shù)據(jù)整理(Pivot相關(guān)函數(shù))
tidy流處理數(shù)據(jù)的大量運用,我想這與管道符%>% 的使用,數(shù)據(jù)處理動詞化,有著很重要的關(guān)系。
用最少的時間,解決最重要的、最常見的問題,我把這稱為是高效;剩余的難點,我把其稱為提高。
1. 列的拆分操作 separate()函數(shù)
separate() 通過在出現(xiàn)分隔符的地方進行拆分,將一列拆分為多列。
示例數(shù)據(jù)
table3
#> # A tibble: 6 x 3
#> country year rate
#> * <chr> <int> <chr>
#> 1 Afghanistan 1999 745/19987071
#> 2 Afghanistan 2000 2666/20595360
#> 3 Brazil 1999 37737/172006362
#> 4 Brazil 2000 80488/174504898
#> 5 China 1999 212258/1272915272
#> 6 China 2000 213766/1280428583
1.1拆分初探
現(xiàn)在要將rate這一列,拆分成兩列,以“/”為分隔符
table3 %>%
separate(rate, into = c("cases", "population"))
#> # A tibble: 6 x 4
#> country year cases population
#> <chr> <int> <chr> <chr>
#> 1 Afghanistan 1999 745 19987071
#> 2 Afghanistan 2000 2666 20595360
#> 3 Brazil 1999 37737 172006362
#> 4 Brazil 2000 80488 174504898
#> 5 China 1999 212258 1272915272
#> 6 China 2000 213766 1280428583
上面的代碼,沒有給出分割的特征符號,這是因為,separate()函數(shù)默認將非字母和非數(shù)字的作為分隔符。因此,上面的代碼默認將“/”視為分隔符。
當然上面的也可以寫成
table3 %>%
separate(rate, into = c("cases", "population"), sep = "/")
參數(shù)sep當中的其實是正則表達式,這個結(jié)合字符串的處理將會變得異常強大。
1.2 拆分后內(nèi)容性質(zhì)的轉(zhuǎn)換
仔細觀察上面的默認轉(zhuǎn)換
默認轉(zhuǎn)換之后的,是字符串類型,而對于這個數(shù)據(jù),我們應該要得到數(shù)字類型,當然這樣的轉(zhuǎn)換,可以在后續(xù)轉(zhuǎn)換。而separate()函數(shù)可以直接完成,如下:
table3 %>%
separate(rate, into = c("cases", "population"), convert = TRUE)
#> # A tibble: 6 x 4
#> country year cases population
#> <chr> <int> <int> <int>
#> 1 Afghanistan 1999 745 19987071
#> 2 Afghanistan 2000 2666 20595360
#> 3 Brazil 1999 37737 172006362
#> 4 Brazil 2000 80488 174504898
#> 5 China 1999 212258 1272915272
#> 6 China 2000 213766 1280428583
2. unite()函數(shù)使用
有分開列的操作就有合并列的操作
示例如下:
table5 %>%
unite(new, century, year)
#> # A tibble: 6 x 3
#> country new rate
#> <chr> <chr> <chr>
#> 1 Afghanistan 19_99 745/19987071
#> 2 Afghanistan 20_00 2666/20595360
#> 3 Brazil 19_99 37737/172006362
#> 4 Brazil 20_00 80488/174504898
#> 5 China 19_99 212258/1272915272
#> 6 China 20_00 213766/1280428583
默認操作函數(shù)中,將兩列連接起來用“_”,如果要改變連接方式,代碼如下:
table5 %>%
unite(new, century, year, sep = "")
#> # A tibble: 6 x 3
#> country new rate
#> <chr> <chr> <chr>
#> 1 Afghanistan 1999 745/19987071
#> 2 Afghanistan 2000 2666/20595360
#> 3 Brazil 1999 37737/172006362
#> 4 Brazil 2000 80488/174504898
#> 5 China 1999 212258/1272915272
#> 6 China 2000 213766/1280428583
同樣很好理解,在相應的地方加上sep參數(shù)。