带有前导 X 字符的迄今为止的字符串
我正在尝试将 Date
列转换为日期格式,但我不断收到错误。我认为问题可能是日期是一个字符并且在年份之前有一个 X:
HMC.Close Date
1 39.71 X2007.01.03
2 40.04 X2007.01.04
3 38.67 X2007.01.05
4 38.89 X2007.01.08
5 38.91 X2007.01.09
6 37.94 X2007.01.10
这是我一直在运行的代码:
stock_honda <- expand.grid("HMC" = HMC$HMC.Close) %>%
"Date" = as.Date(row.names(as.data.frame(HMC))) %>%
subset(Date >"2021-02-28" & Date < "2022-03-11")
charToDate(x) 中的错误: 字符串不是标准的明确格式
I'm trying to convert the Date
column to date format but I keep getting an error. I think the problem might be that the date is a character and has an X before the year:
HMC.Close Date
1 39.71 X2007.01.03
2 40.04 X2007.01.04
3 38.67 X2007.01.05
4 38.89 X2007.01.08
5 38.91 X2007.01.09
6 37.94 X2007.01.10
This is the code I've been running:
stock_honda <- expand.grid("HMC" = HMC$HMC.Close) %>%
"Date" = as.Date(row.names(as.data.frame(HMC))) %>%
subset(Date >"2021-02-28" & Date < "2022-03-11")
Error in charToDate(x) :
character string is not in a standard unambiguous format
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
gsub
首先删除导致问题的“X”,然后使用lubridate
包中的ymd
将字符串转换为日期。此外,您可以使用 dplyr 包中的 mutate(across(...)) 进行转换,以 tidyverse 方式完成所有操作。You can use
gsub
to first remove the "X" that is causing a problem and then useymd
fromlubridate
package to convert the strings into Dates. Additionally, you can make that conversion usingmutate(across(...))
from thedplyr
package to do everything in a tidyverse-way.这是一个首先避免在日期前添加“X”的管道:
如果有一个
Between 版本可以避免显式转换为日期,那就太好了。 (
filter("2021-02-28" < Date, Date < "2022-03-11")
也适用于最后一步。)Here is a pipeline that avoids prepending "X" to the dates in the first place:
It would be nice if there were a version of
between
that avoided the need to explicitly convert to dates. (filter("2021-02-28" < Date, Date < "2022-03-11")
would also work for the last step.)