R 語言簡單資料處理和分析
實驗目標:
透過對朝陽醫院2016年銷售資料進行處理和分析,獲得以下4個指標:月均消費次數、月均消費金額、客單件、消費趨勢
實驗材料:
朝陽醫院2016年銷售資料。xlsx
packages:openxlsx 和 stringr
實驗步驟:
1,選用 openxlsx 讀取 Excel資料
#安裝packages(“openxlsx”)
install。packages(“openxlsx”)
library(“openxlsx”)
#讀取資料
#指定資料路徑
readFilePath <- “/Users/chaorenbuhuifei/Documents/workspace/bigdata/闖關遊戲課程《從零學會大資料核心:資料分析》/第3關:簡單資料處理和分析/原始碼和資料/朝陽醫院2016年銷售資料。xlsx”
sellData <- read。xlsx(readFilePath,sheet = 1)
2,資料預處理
2。1 列名重新命名
#考慮到R對中文支援不太好以及便於編寫程式碼,對列進行重新命名
names(sellData) <-c(“time”,“SscNo”,“drugCode”,“drugName”,“sellAmount”,“receivables”,“received”)
2。2 刪除缺失資料
#刪除所有含有缺失資料的行,此處僅刪除time為空的記錄
sellData <- sellData[!is。na(sellData$time),]
2。3 處理日期
#處理日期
#選用 R語言
字串
處理包stringr
library(stringr)
timesplit <- str_split_fixed(sellData$time,“ ”,n=2) #此處注意,雙引號之間是空格
sellData$time <- timesplit[,1]
2。4
資料型別轉換
#資料型別轉換
class(sellData$time)
sellData$time <- as。Date(sellData$time,“%Y-%m-%d”)
class(sellData$time)
2。5 資料排序
#按照時間升序排列
sellData <- sellData[order(sellData$time,decreasing = FALSE),]
3,獲得4個指標
根據4個指標來看,我們需要獲取總消費次數、總月份、總消費金額
#同一天內,同一個人發生的所有消費算作一次消費,因此需要先根據此條件進行資料去重
kpi1 <- sellData[!duplicated(sellData[,c(“time”,“SscNo”)]),
#透過
nrow函式
獲取總消費次數
consumerNumber <- nrow(kpi1)
#開始獲取總月份處理
starttime <- kpi1$time[1]
endtime <- kpi1$time[nrow(kpi1)]
day <- endtime - starttime
# ‘%%’對“difftime”物件不適用,必須先轉換為numeric
month <- as。numeric(day) %/% 30
3。1 計算月均消費次數
#月均消費次數 等於 總消費次數 除以總月份
monthConsume <- consumerNumber / month
3。2 計算
月均消費金額
#月均消費金額等於 總消費金額處以總月份
totalMoney <- sum(sellData$received,na。rm = TRUE)
monthMoney <- totalMoney / month
monthMoney
3。3 計算客單價
#客單價等於 總消費金額/總消費次數
pct <- totalMoney / consumerNumber
3。4 繪製
消費趨勢
#消費趨勢
week <- tapply(sellData$received,
format(sellData$time,“%Y-%U”),
sum)
week
week <-as。data。frame。table(week)
names(week) <- c(“time”,“recevied”)
week$time <- as。character(week$time)
week$timeNumber <- c(1:nrow(week))
#注意,如果Plot遇到中文亂碼,請用
family引數
指定下本地計算機中的中文字型即可
plot(week$timeNumber,week$recevied,
family = ‘STFangsong’,
xlab = “時間(年份-第幾周)”,
ylab =“消費金額”,
xaxt = “n”,
main = “2016年朝陽醫院消費曲線”,col。main = “red”,
col = “blue”,
type = “b”)
axis(1,at=week$timeNumber,labels = week$time,cex。axis = 1。5)
總結:
1,透過本次練習,複習了簡單資料處理的基本步驟 依次為列名重新命名、刪除缺失的資料、處理日期、資料型別轉換、資料排序
2,透過本次練習,複習了列名重新命名函式、資料型別轉換函式、排序函式、
字串處理函式
、sum 函式、分組函式tapply
3,透過本次練習,複習了Plot 繪圖
4,sellData[order(sellData$time,decreasing = FALSE),] 實驗結果是按照時間生序排列,而非學習文件中所說的
降序排列
5,Plot繪圖會遇到中文亂碼的問題,實質在於未指定中文字型。本人使用
mac 電腦
解決方案是用family引數指定下本地計算機中已安裝的中文字型。
延伸:如何檢視mac中已安裝的中文字型
command + 空格 調出搜尋,錄入 字型
雙擊字型冊
檢視字型的PostScript名稱,family 引數指定時候填寫PostScript名稱
6,知乎文章複製過來的程式碼,一般不要直接在R 中執行,會有意想不到的錯誤。