iT邦幫忙

2024 iThome 鐵人賽

DAY 20
0
自我挑戰組

R語言初學紀錄系列 第 20

DAY20-R語言 資料處理dplyr套件part.2 函式應用

  • 分享至 

  • xImage
  •  

前言:接下來要練習如何應用dplyr套件中的各個函數,我是參考以下網址的練習,但某些變數會修改!如果內容有哪些錯誤的地方,請多多包涵~


正文開始-->
【安裝套件】
首先要先安裝兩個套件,分別為dplyr套件以及gapminder套件處理的資料源。
完整程式碼:

install.packages("dplyr")##安裝dplyr套件
library(dplyr)##載入dplyr套件
install.packages("gapminder")##安裝載入gapminder資料源
library(gapminder)

【檢視資料】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228NBr02T7JJ9.png

  • 使用head()str()函數檢視gapminder資料。
  • 有六個欄位包含:country國家、continent所在洲、year年份、lifeExp:平均預期壽命、pop:人口總數、gdpPercap人均國內生產總值 (GDP per capita)。

【篩選觀測值】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228gDunT0jyLR.png

  • 使用filter()函數篩選1997年的資料。

【選擇變數】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228hD1B8rJ5By.png

  • 使用select()函數,輸入資料框的名稱,以及想要選取的變數名稱。在此舉例gapminder 中的 country。

【新增欄位】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228UIp0hoCclJ.png

  • 使用mutate()函數新增變數,在此新增pop_in_hundred。

【排序觀測值】
https://ithelp.ithome.com.tw/upload/images/20240918/201692281VjTD0bjWj.png

  • 使用arrange()函數依指定的變數來排序觀測值。

【計算統計值】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228rnv0787fc6.png

  • 使用summarise()函數計算1997年全球人口數。

【依類別變數分組】
https://ithelp.ithome.com.tw/upload/images/20240918/20169228PjaLRxoWxC.png

  • 使用group_by()函數以大洲分組,並使用summarise()函數計算每個洲的平均壽命。

參考:

  1. https://yijutseng.github.io/DataScienceRBook/eda.html#dplyr
  2. https://bookdown.org/jefflinmd38/r4biost/basictidy.html
  3. https://bookdown.org/tonykuoyj/eloquentr/dplyr.html

上一篇
DAY19-R語言 資料處理dplyr套件part.1 介紹
下一篇
DAY21-R語言 資料視覺化part.1
系列文
R語言初學紀錄22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言