R 如何在日期列中为月、日和年创建单独的列?
我有500行带有日期列,第一行是2018-10-17。 我想为日、月和年创建单独的列。R 如何在日期列中为月、日和年创建单独的列?,r,R,我有500行带有日期列,第一行是2018-10-17。 我想为日、月和年创建单独的列。 日期列的类别是Factor。您可以使用stru extract从库stringr: date <- "2018-10-17" library(stringr) df <- data.frame( year = str_extract(date, "^\\d{4}"), month = str_extract(date, "(?<=-
日期列的类别是Factor。您可以使用
stru extract
从库stringr
:
date <- "2018-10-17"
library(stringr)
df <- data.frame(
year = str_extract(date, "^\\d{4}"),
month = str_extract(date, "(?<=-)\\d{2}(?=-)"),
day = str_extract(date, "(?<=-)\\d{2}$")
)
df
year month day
1 2018 10 17
df <- data.frame(
year = format(as.Date(date, "%Y-%m-%d"), "%Y"),
month = format(as.Date(date, "%Y-%m-%d"), "%m"),
day = format(as.Date(date, "%Y-%m-%d"), "%d")
)