我有一個df以character格式存盤日期的列,我想為其提取月份。為此,我使用以下內容:
mutate(
Date = as.Date(
str_remove(Timestamp, "_.*")
),
Month = month(
Date,
label = F)
)
但是,10 月、11 月和 12 月存盤的月份前面有一個額外的零。圖書館lubridate不認識它。如何調整上面的代碼來解決這個問題?這是我的Timestamp專欄:
c("2021-010-01_00h39m", "2021-010-01_01h53m", "2021-010-01_02h36m",
"2021-010-01_10h32m", "2021-010-01_10h34m", "2021-010-01_14h27m"
)
uj5u.com熱心網友回復:
首先將值轉換為日期并用于format從中獲取月份。
format(as.Date(x, '%Y-0%m-%d'), '%b')
#[1] "Oct" "Oct" "Oct" "Oct" "Oct" "Oct"
%b給出縮寫的月份名稱,您也可以使用%Bor%m取決于您的選擇。
format(as.Date(x, '%Y-0%m-%d'), '%B')
#[1] "October" "October" "October" "October" "October" "October"
format(as.Date(x, '%Y-0%m-%d'), '%m')
#[1] "10" "10" "10" "10" "10" "10"
uj5u.com熱心網友回復:
一種方法是strsplit提取第二個元素:
month.abb[readr::parse_number(sapply(strsplit(x, split = '-'), "[[", 2))]
這將回傳:
#"Oct" "Oct" "Oct" "Oct" "Oct" "Oct"
資料:
c("2021-010-01_00h39m", "2021-010-01_01h53m", "2021-010-01_02h36m",
"2021-010-01_10h32m", "2021-010-01_10h34m", "2021-010-01_14h27m"
) -> x
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434259.html
