R:如何从日期中删除日期?
R: How to remove the day from a date?
我在 df 列中有一堆日期,格式如下:dd.mm.yyyy
我希望它看起来像这样:01/2020 (mm.yyyy)
如何从所有日期中删除这一天?
使用format
指定您想要的日期格式
date <- as.Date("13/01/2020", format = "%d/%m/%Y")
format(date, "%m/%Y")
[1] "01/2020"
编辑 - 应用于数据框列
dates <- c("13/01/2020", "17/02/2015", "13/03/2013")
df <- data.frame(dates, stringsAsFactors = FALSE)
df$dates <- as.Date(df$dates, format = "%d/%m/%Y")
df$dates_format <- format(df$dates, "%m/%Y")
df
dates dates_format
1 2020-01-13 01/2020
2 2015-02-17 02/2015
3 2013-03-13 03/2013
除了 的 format
之外,另一个选项是使用 sub
,如下所示
> sub(".*?/","","13/01/2020")
[1] "01/2020"
R 中有明确的日期格式化选项(参见 Greg 的回答)。另一种选择是将日期分成 3 列,然后重新组合月份和年份,在两者之间放置一个 /。请注意,这会将新的日期列保留为字符格式,您可能需要根据需要进行更改。
library(tidyr)
df <- data.frame(date = "13/01/2020")
df <- separate(df, date, into = c("day","month","year"), sep = "/")
df$newdate <- paste(df$month, df$year, sep = "/")
这是使用 lubridate
的解决方案。
library(lubridate)
#Set the desired format (mm-yyyy) as my_stamp
my_stamp<-stamp( "02-2019",
orders = "my")
#A df with a column full of dates
df <- data.frame(dates = c("30/04/2020","29/03/2020","28/02/2020"))
#Change the column from string to date format
df$dates<-dmy(df$dates)
#Apply the format you desire to the dates (i.e., only month and year)
df$dates<-my_stamp(df$dates)
# dates
#1 04-2020
#2 03-2020
#3 02-2020
我在 df 列中有一堆日期,格式如下:dd.mm.yyyy
我希望它看起来像这样:01/2020 (mm.yyyy)
如何从所有日期中删除这一天?
使用format
指定您想要的日期格式
date <- as.Date("13/01/2020", format = "%d/%m/%Y")
format(date, "%m/%Y")
[1] "01/2020"
编辑 - 应用于数据框列
dates <- c("13/01/2020", "17/02/2015", "13/03/2013")
df <- data.frame(dates, stringsAsFactors = FALSE)
df$dates <- as.Date(df$dates, format = "%d/%m/%Y")
df$dates_format <- format(df$dates, "%m/%Y")
df
dates dates_format
1 2020-01-13 01/2020
2 2015-02-17 02/2015
3 2013-03-13 03/2013
除了 format
之外,另一个选项是使用 sub
,如下所示
> sub(".*?/","","13/01/2020")
[1] "01/2020"
R 中有明确的日期格式化选项(参见 Greg 的回答)。另一种选择是将日期分成 3 列,然后重新组合月份和年份,在两者之间放置一个 /。请注意,这会将新的日期列保留为字符格式,您可能需要根据需要进行更改。
library(tidyr)
df <- data.frame(date = "13/01/2020")
df <- separate(df, date, into = c("day","month","year"), sep = "/")
df$newdate <- paste(df$month, df$year, sep = "/")
这是使用 lubridate
的解决方案。
library(lubridate)
#Set the desired format (mm-yyyy) as my_stamp
my_stamp<-stamp( "02-2019",
orders = "my")
#A df with a column full of dates
df <- data.frame(dates = c("30/04/2020","29/03/2020","28/02/2020"))
#Change the column from string to date format
df$dates<-dmy(df$dates)
#Apply the format you desire to the dates (i.e., only month and year)
df$dates<-my_stamp(df$dates)
# dates
#1 04-2020
#2 03-2020
#3 02-2020