我在df列中有一堆日期,格式如下:dd.mm.yyyy
我希望它看起来像这样:01/2020(mm.yyyy)
如何从所有日期中删除日期?
答案 0 :(得分:4)
使用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
答案 1 :(得分:2)
除了@Greg的format
之外,另一个选择是使用sub
如下
> sub(".*?/","","13/01/2020")
[1] "01/2020"
答案 2 :(得分:0)
R中有明确的日期格式选项(请参阅Greg的答案)。另一种选择是将日期分成三列,然后重新组合月份和年份,并在其之间插入一个/。请注意,这会将新日期列保留为字符格式,您可能需要根据需要进行更改。
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 = "/")
答案 3 :(得分:0)
这是使用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