gpt4 book ai didi

r - 将日期变量更改为连续月份

转载 作者:行者123 更新时间:2023-12-04 18:58:28 25 4
gpt4 key购买 nike

我有一个名为“Date”的列的数据框,该列采用日期格式:

 df<- data.frame(date=c("1997-01-01", "1997-01-02", "1997-01-03", "1997-01-04", 
"1997-01-05", "1997-01-06" ,"1997-01-07" ,"1997-01-08","1998-01-12",
"1998-01-13", "1998-01-14", "1998-01-15" ,"1998-01-16", "1998-01-17",
"1998-01-18", "1998-01-19"))

我需要制作一个列来更改 Date 中唯一的年/月组合。列到一个连续的月份变量。我有 20 年的数据,从 1 到 240 有几个月。

因此,上面 df 的示例将返回:
output<- data.frame(date=c("1997-01-01", "1997-01-02", "1997-01-03", 
"1997-01-04", "1997-01-05", "1997-01-06" ,"1997-01-07" ,"1997-01-08","1998-01-12",
"1998-01-13", "1998-01-14", "1998-01-15" ,"1998-01-16", "1998-01-17",
"1998-01-18", "1998-01-19"), continuous_month=c("1", "1", "1", "1",
"1", "1" ,"1" ,"1","13", "13", "13", "13" ,"13", "13", "13", "13"))

注意:01/1997 将是第一个月,我在示例数据框中跳过了 02/1997(第 2 个月)-12/1997(第 12 个月),因此 01/1998 将是该系列的第 13 个月。

最佳答案

您可以使用 yearmonthlubridate提取相关信息

library(lubridate)
df$date = ymd(df$date)
temp = 12*(year(df$date) - min(year(df$date))) + month(df$date)
df$output = temp - min(temp) + 1
df$output
# [1] 1 1 1 1 1 1 1 1 13 13 13 13 13 13 13 13

关于r - 将日期变量更改为连续月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46044350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com