我有一个包含多个列的dataframe df
。一列Dates
包含许多不同日期格式的字符串值。它包含德语日期格式(即6. 2022年6月或5. 2019年8月)、英语日期格式(即2019年4月5日或2019年3月4日),它包含两种格式的日期,而不需要添加当前年份(即1月2日或15日此外,它还包含两种语言的小时数(即2标准品或3小时)。
我首先想将日期转换为一种格式(最好是英语标准yyyy-mm-dd),然后添加一个新列Time_since
,用于计算从Dates
到现在的小时数。例如,如果我有日期16。2023年5月(所以昨天在德国格式)我想在新列24(因为我没有具体的时间,我假设全天2023-05-17)。如果我有10小时或10标准。那我只想要10分
这是我的dataframe的dput()
:
structure(list(Dates = c("1h", "10 Std.", "Apr 5", "Dec 8, 2022",
"May 30, 2019", "6. Juni 2021", NA, "15. März", "13. Aug. 2019"
)), class = "data.frame", row.names = c(NA, -9L))
输出应该是这样的:
Dates Time_since
1h 1
10 Std. 10
2023-04-05 1008
2022-12-08 3840
2019-05-30 25800
2021-06-06 17040
NA NA
2023-03-15 1512
2019-08-13 24192
你知道我怎么能一次把这么多的变形结合起来吗?
2条答案
按热度按时间yqhsw0fo1#
你应该尽可能地把单词(月,小时)从德语翻译成英语。要将日期转换为标准化格式并计算从日期到现在的小时数,可以使用R中的lubridate包。如果日期具有特定的时区,则可能需要相应地调整代码。
我无法完美地转换所有日期,但我认为这至少可以帮助你朝着正确的方向发展。请记住相应地更改'origin'参数。祝你好运!
vuktfyat2#
我自己得到了答案,但也许有人可以以某种方式缩短这个代码。我只是添加了许多不同的步骤和列来得到答案