--- title: 'R 語言學習心得-dplyr應用' disqus: hackmd --- R dplyr應用 自動點名篇 === ![downloads](https://img.shields.io/badge/download-R-brightgreen) ![grade](https://img.shields.io/badge/Grade-新手-brightgreen) ![chat](https://img.shields.io/discord/:serverId.svg) --- ## Beginners Guide 解決問題 === 1. 修課學生名單 vs 當天有到的學生名單 2. 將缺席學生註記"x" & 出席學生註記"o" 3. 最後生成一個新的csv輸出(所有學生的出缺席狀況) ---- ```r= getwd() setwd("C:\\Users\\user\\Desktop") getwd() # setting output_file <- "output.csv" # import csv library(dplyr) library(tidylog) class <- read.csv("class.csv",fileEncoding = "UTF-8-BOM") class attendence <- read.csv("today.csv",fileEncoding = "UTF-8-BOM") attendence # compare abscence <- anti_join(class,attendence) abscence abscence <- abscence %>% mutate(attendence = "x") new_class <- left_join(class,abscence) new_class # turn <NA> into "o" new_class$attendence[is.na(new_class$attendence)]<- "o" new_class # output csv write.csv(new_class,file= output_file,row.names = FALSE) ``` ---- 結果 === **data** ==注意: 出席名單的排序方式不一定與修課名單相同== ![](https://i.imgur.com/9X31QXq.jpg) **成果** ![](https://i.imgur.com/aCwMUGf.jpg) ---- code解釋 === ```r= fileEncoding = "UTF-8-BOM" ``` :::warning 這邊read.csv加上這行是為了不要出現亂碼 有時候直接read 可以,但有時候不行 ::: ```r= anti_join(class,attendence) left_join(class,abscence) ``` :::success 這邊詳情可以參考[這裡](https://r3dmaotech.blogspot.com/2016/09/r-data-frame-merge-join.html) 簡單說,anti = 找不同 = 找缺席 left join 則是以class的row為主,跟abscence合併 合併後,缺席的人會有x,但是因為出席的人attendence那欄沒有賦值 所以是NA ::: ```r= new_class$attendence[is.na(new_class$attendence)]<- "o" ``` :::info 原本這邊我是想用for寫,但是R的for好像不接受NA 所以改用這種找出NA值然後接改的方式 ::: ---- ==小結== 也不知道這樣寫484比較快的寫法 但是現階段看來還行,行數也不多 --- ## More tutorial / note 1. [my coding-blog](fatcatcat-lab.blogspot.com) 2. [my movie-blog](fatcatcat-movie.blogspot.com) ###### tags: `R` `beginner` `cat` `tutorial`