簡體   English   中英

如何將列表中的 df 字符列轉換為特定的日期格式?

[英]how to convert df character columns inside a list to an specific date format?

假設列表中包含字符日期列的下一個 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)

然后我得到一個 function 刪除“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)
  }
   
   
 }

function 適用於單個輸入,例如convert_columns_to_date("2021-11-01 UTC")返回正確的格式"01/11/2021"

但是,當 function 應用於列表中 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) 中的錯誤:字符串不是標准的明確格式

為什么會發生此錯誤? 有什么辦法可以解決嗎?

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)

另一種可能性,使用lubridatedplyr

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM