目錄
原始文章
R語言-檢視變數及資料型態所佔記憶體容量,零成本提高計算效率
對資料科學家或數據分析師來說,資料量太大、電腦效能不足一直都是個痛,經常要小心翼翼地觀察記憶體使用率是不是快爆炸。然而,就我的觀察,一樣都是撰寫程式,資料科學工作者對於程式碼乾淨、易懂、高效率的追求似乎比其他工程師來得低。(或是我的樣本數不足,以偏概全)
其實,只要善用一些小工具,把檔案很大但用不到的物件清掉,並留意哪一種資料型態(Data Type)的容量較輕巧,就可以在不花錢升級電腦硬體的條件下,提升計算效率,也更有可能執行更複雜的計算。
來吧,直接複製貼上
check_file_size <- function(name){
size <- object.size(get(name))
# 4496535920 bytes = 4496 mb
if(size >= 1000000){
unit_size <- 1000000
unit <- "mb"
}else if(size >= 1000){
unit_size <- 1000
unit <- "kb"
}else{
unit_size <- 1
unit <- "byte"
}
size <- size / unit_size
size <- round(size)
cat(paste0(name, " ", size, " ", unit))
}
檢查資料型態(Data Type)的容量大小
# Compare Date and Number
> t1 <- Sys.Data()
> t2 <- 20200101
> check_file_size("t1", unit = "byte")
t1 256 byte
> check_file_size("t2",unit = "byte")
t2 48 byte
# Compare numeric and character for ID
> test <- as.numeric(870576)
> test2 <- as.character(870576)
> check_file_size("test", unit = "byte")
test 48 byte
> check_file_size("test2", unit = "byte")
test2 96 byte
實際應用
由於完整的日期格式實在是太暫記憶體空間了,所以我習慣做日期計算後,會同時保留完整的日期格式,以及Integer型態,後者拿來標記大量資料或是SQL時都很好用。
cal_date <- function(date, amount = 0, type = "m"){
library(lubridate)
# 轉換為日期格式
date = ymd(date)
# 日期計算 ...................
if(type == "y" | type == "years" | type == "year"){
new_date <- date %m+% years(amount)
}else if(type == "m" | type == "months" | type == "month"){
new_date <- date %m+% months(amount)
}else if(type == "w" | type == "weeks" | type == "week"){
new_date <- date %m+% weeks(amount)
}else if(type == "d" | type == "days" | type == "day"){
new_date <- date %m+% days(amount)
}
# 資料合併 ...................
new_date_num <- str_replace_all(new_date, "-", "")
# 如果使用vector合併時,2019-06-02會被轉成數字18049,因此用list合併。
return_list <- list(new_date_num, new_date)
return(return_list)
}
# 範例
ex1 <- cal_date(20190101, -1, "m")
ex2<- cal_date(20190101)