我有一个包含一列日期对象的数据框架。我怎样才能得到一个月的数字的新列?例如:January ->2月1日->2…
我还需要一个包含每月每天数字的新列。示例:2022-01-01 ->1、2022-01-02 - 2
您可以使用以下代码:
df = data.frame(date = as.Date(c("2022-01-01", "2022-01-02")))
df[, "month"] <- format(df[,"date"], "%m")
df
输出:
date month
1 2022-01-01 01
2 2022-01-02 01
我确信R中有特定于日期对象的解决方案,但我从未使用过它们。基数R解:
splitDates <- function( date ) {
day <- gsub('^0+','',unlist(strsplit(date,'-'))[2])
month <- gsub('^0+','',unlist(strsplit(date,'-'))[3])
return(list(day,
month))
}
require(tidyverse)
require(lubridate)
示例数据:
# A tibble: 13 × 1
date
<date>
1 2022-04-28
2 2022-05-28
3 2022-06-28
4 2022-07-28
5 2022-08-28
6 2022-09-28
7 2022-10-28
8 2022-11-28
9 2022-12-28
10 2023-01-28
11 2023-02-28
12 2023-03-28
13 2023-04-28
一个可能的解决方案:
df %>%
mutate(
month = month(date),
month_name = month(date, label = TRUE, abbr = FALSE),
day = day(date),
week = week(date)
)
输出:
# A tibble: 13 × 5
date month month_name day week
<date> <dbl> <ord> <int> <dbl>
1 2022-04-28 4 April 28 17
2 2022-05-28 5 May 28 22
3 2022-06-28 6 June 28 26
4 2022-07-28 7 July 28 30
5 2022-08-28 8 August 28 35
6 2022-09-28 9 September 28 39
7 2022-10-28 10 October 28 43
8 2022-11-28 11 November 28 48
9 2022-12-28 12 December 28 52
10 2023-01-28 1 January 28 4
11 2023-02-28 2 February 28 9
12 2023-03-28 3 March 28 13
13 2023-04-28 4 April 28 17