从dataframe将日期转换为相应月份的第一天
我有一个名为df的数据帧 我需要将每个日期转换为该月的第一天从dataframe将日期转换为相应月份的第一天,r,R,我有一个名为df的数据帧 我需要将每个日期转换为该月的第一天 Date Sales 02-12-2018 1000 03-11-2019 2000 24-08-2010 3000 预期产量 Date Sales Date2 02-12-2018 1000 01-12-2018 03-11-2019 2000 01-11-2019 24-08-2010 3000 01-08-2010 等等。在R中,我似
Date Sales
02-12-2018 1000
03-11-2019 2000
24-08-2010 3000
预期产量
Date Sales Date2
02-12-2018 1000 01-12-2018
03-11-2019 2000 01-11-2019
24-08-2010 3000 01-08-2010
等等。在R中,我似乎无法做到这一点。转换为日期并使用
loor\u date
fromlubridate
library(lubridate)
floor_date(dmy(df$Date), 'month')
#[1] "2018-12-01" "2019-11-01" "2010-08-01"
library(anydate)
format(anydate(df$Date), "%01-%m-%Y")
数据
df <- structure(list(Date = structure(1:3, .Label = c("02-12-2018",
"03-11-2019", "24-08-2010"), class = "factor"), Sales = c(1000L,
2000L, 3000L)), class = "data.frame", row.names = c(NA, -3L))
df转换为日期并使用floor\u date
fromlubridate
library(lubridate)
floor_date(dmy(df$Date), 'month')
#[1] "2018-12-01" "2019-11-01" "2010-08-01"
library(anydate)
format(anydate(df$Date), "%01-%m-%Y")
数据
df <- structure(list(Date = structure(1:3, .Label = c("02-12-2018",
"03-11-2019", "24-08-2010"), class = "factor"), Sales = c(1000L,
2000L, 3000L)), class = "data.frame", row.names = c(NA, -3L))
df您可以将日期转换为日期,然后在日期槽中用“01”格式化日期
format(as.Date(df$Date, "%d-%m-%Y"), "%01-%m-%Y")
# [1] "01-12-2018" "01-11-2019" "01-08-2010"
您可以将日期转换为日期,然后在日期槽中使用“01”格式设置日期
format(as.Date(df$Date, "%d-%m-%Y"), "%01-%m-%Y")
# [1] "01-12-2018" "01-11-2019" "01-08-2010"
我们也可以使用一个简单的正则表达式来实现这一点(使用@Ronaksah提供的数据)
我们也可以使用一个简单的正则表达式来实现这一点(使用@Ronaksah提供的数据)
带有anydate
library(lubridate)
floor_date(dmy(df$Date), 'month')
#[1] "2018-12-01" "2019-11-01" "2010-08-01"
library(anydate)
format(anydate(df$Date), "%01-%m-%Y")
带有anydate
library(lubridate)
floor_date(dmy(df$Date), 'month')
#[1] "2018-12-01" "2019-11-01" "2010-08-01"
library(anydate)
format(anydate(df$Date), "%01-%m-%Y")