假設串列中包含字符日期列的下一個 df:
df<- data.frame(dates=c("2021-12-31 UTC", "2021-12-27 UTC", "2021-12-26 UTC", NA),
another_column_with_dates=c("2021-11-21 UTC",
"2021-12-12", "2021-11-01 UTC", NA))
list_of_df <- list(df=df)
然后我得到了一個洗掉“UTC”和空格的函式,然后它將日期轉換為特定格式"%d/%m/%Y:
convert_columns_to_date <- function(x){
if(is.na(x)){
return(NA)
}
else if(!is.na(x)){
# remove white-spaces and extra strings
x<- trimws(gsub("UTC", "", x))
# date format: %d/%m/%Y
x<- format(as.Date(x), "%d/%m/%Y")
return(x)
}
else {
return(NA)
}
}
該函式適用于單個輸入,例如convert_columns_to_date("2021-11-01 UTC")回傳正確的格式"01/11/2021"。
但是,當該函式應用于串列中 df 中的所有列時:
date_columns_input <- c('dates', 'another_column_with_dates')
for(i in 1:length(list_of_df[["df"]][date_columns_input])){
list_of_df[["df"]][i]<- convert_columns_to_date(list_of_df["df"][i])
}
出現下一個錯誤:
charToDate(x) 中的錯誤:字串不是標準的明確格式
為什么會發生此錯誤?有什么辦法可以解決嗎?
uj5u.com熱心網友回復:
1) lapply如圖所示使用 format_vec,然后在 df 中的 ix 列上進行 lapply。請注意, as.Date 已經在末尾洗掉了垃圾,通常最好不要覆寫物件,以便在不重新生成輸入的情況下輕松重新運行。ix 應指定為列號或名稱的向量。
ix <- 1:2
format_vec <- function(x) format(as.Date(x), format = "%d/%m/%Y")
L <- list_of_df
L$df[ix] <- lapply(L$df[ix], format_vec)
L
給予:
$df
dates another_column_with_dates
1 31/12/2021 21/11/2021
2 27/12/2021 12/12/2021
3 26/12/2021 01/11/2021
4 <NA> <NA>
2)回圈如果您更喜歡使用回圈,那么:
ix <- 1:2
L <- list_of_df
for(i in ix) L$df[[i]]<- format_vec(L$df[[i]])
3)dplyr
library(dplyr)
L <- list_of_df
L$df <- L$df %>% mutate(across(1:2, format_vec))
4) 崩潰
library(collapse)
L <- list_of_df
L$df <- ftransformv(L$df, 1:2, format_vec)
uj5u.com熱心網友回復:
另一種可能性,使用lubridateand dplyr:
library(dplyr)
library(lubridate)
list_of_df$df %>%
mutate(across(everything(), ~ ymd(.x) %>% format("%d/%m/%Y")))
#> dates another_column_with_dates
#> 1 31/12/2021 21/11/2021
#> 2 27/12/2021 12/12/2021
#> 3 26/12/2021 01/11/2021
#> 4 <NA> <NA>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411010.html
標籤:
下一篇:用日歷減去天數不會減少年份?
