gpt4 book ai didi

r - R-将日期值转换为正整数

转载 作者:行者123 更新时间:2023-12-02 08:06:16 25 4
gpt4 key购买 nike

希望有人可以指出我的解决方案,以解决我的特定问题。

假设我有一个数据框,在A列中,我有格式为(YYYY-MM-DD,POSIXct)的日期,该日期介于某个起点和终点之间(即2017/01/01至2018/01/01)。在BI列中有一个项目列表,在CI列中有一个在A中给出的日期的项目数量。此外,我想添加一个假设,即尽管A列中的日期介于已知的开始日期和结束日期之间,并且顺序不一,它们不一定要以相等的时间间隔分开。一个例子可能看起来像这样:

+------------+-------+----------+
| Date | Item | Quantity |
+------------+-------+----------+
| 2017/01/01 | Beans | 2 |
| 2017/01/01 | Pens | 4 |
| 2017/01/04 | Beans | 3 |
| 2017/01/04 | Pens | 5 |
| 2017/02/01 | Tubes | 4 |
| 2017/02/03 | Beans | 9 |
+------------+-------+----------+

我想做的是添加一列,将A列中的每个日期转换为一个正整数,该整数与给定开始日期以来的天数相对应。例如,如果开始日期是2017/01/01,我想添加以下列
+------------+-------+----------+------+
| Date | Item | Quantity | Days |
+------------+-------+----------+------+
| 2017/01/01 | Beans | 2 | 1 |
| 2017/01/01 | Pens | 4 | 1 |
| 2017/01/04 | Beans | 3 | 4 |
| 2017/01/04 | Pens | 5 | 4 |
| 2017/01/08 | Tubes | 4 | 8 |
| 2017/01/09 | Beans | 9 | 9 |
+------------+-------+----------+------+

有没有一种简单的解决方案,可以利用R的内部日期/时间处理方式(尤其是月份/ year年中的天数等)?

这是评论者要求的dput()
structure(list(date = structure(c(17167, 17167, 17170, 17170, 17174, 
17175), class = "Date"), item = structure(c(1L, 2L, 1L, 2L, 3L, 1L),
.Label = c("Beans", "Pens", "Tubes"), class = "factor"), quantity =
c(2, 4, 3, 5, 4, 9)), class = "data.frame", row.names = c(NA, -6L))

预先感谢您的帮助,希望我的问题可以理解。

最佳答案

# Example data (please make it reproducible like this in future questions):

yourdata <-
data.frame(Quantity = c(2,4,3,5,4,9),
Item = c('Beans', 'Pens', 'Beans', 'Pens', 'Tubes', 'Beans'),
Date = c("2017/01/01", "2017/01/01","2017/01/04", "2017/01/04", '2017/01/01', "2017/01/09")
)


yourdata$difftime <- sapply(yourdata$Date, difftime, yourdata$Date[1]) + 1

  Quantity  Item       Date difftime
1 2 Beans 2017/01/01 1
2 4 Pens 2017/01/01 1
3 3 Beans 2017/01/04 4
4 5 Pens 2017/01/04 4
5 4 Tubes 2017/01/08 8
6 9 Beans 2017/01/09 9


这也适用于您添加的 dput()数据:
yourdata <- structure(list(date = structure(c(17167, 17167, 17170, 17170, 17174, 
17175), class = "Date"), item = structure(c(1L, 2L, 1L, 2L, 3L, 1L),
.Label = c("Beans", "Pens", "Tubes"), class = "factor"), quantity =
c(2, 4, 3, 5, 4, 9)), class = "data.frame", row.names = c(NA, -6L))

yourdata$difftime <- sapply(yourdata$date, difftime, yourdata$date[1]) + 1

yourdata

        date  item quantity difftime
1 2017-01-01 Beans 2 1
2 2017-01-01 Pens 4 1
3 2017-01-04 Beans 3 4
4 2017-01-04 Pens 5 4
5 2017-01-08 Tubes 4 8
6 2017-01-09 Beans 9 9

关于r - R-将日期值转换为正整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51143868/

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