目錄
原始文章
在R語言中,基本上每個Function只能回傳一個物件,如果希望回傳多個物件,就必須讓回傳物件的資料型態(Data Type)為清單(List)或向量(Vector)。
來吧,複製貼上
回傳向量(Vector)
test_function <- function(){
return_list <- c()
return_list[1] <- 1
return_list[2] <- 2
return_list[5] <- 10
return(return_list)
}
test <- test_function()
test
>
[1] 1 2 NA NA 10
回傳清單(List)
return_list <- function(){
test <- list()
test[1] <- "a"
test[2] <- "b"
return(test)
}
test <- return_list()
test
>
[[1]]
[1] "a"
[[2]]
[1] "b"
實際應用
我在〈檢視變數及資料型態所佔記憶體容量,零成本提高計算效率〉中提過,日期格式的物件,像是as.Date(“2020-04-02”),所占的記憶體容量是256 byte,但轉成integer格式,也就是20200402後,容量會降到48 byte。這個認知在處理大量資料時非常重要,而以下的程式碼就是我用來處理這個問題的function。
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)
Muchas gracias. ?Como puedo iniciar sesion?
2021-03-17
00:00:54