【问题标题】:Error as.POSIXlt.character() when using lubridate使用 lubridate 时出现 as.POSIXlt.character() 错误
【发布时间】:2022-11-25 04:01:41
【问题描述】:

我正在加载一个股票价格数据集,如下所示:

stockprices <- data.frame (Names Date  = c("1985-05-31", "1985-05-31", ...),
                  Ticker Symbol = c("AMFD", "AMT", ...),
                  Price = c(5.875, 14.375...)
                  )

我正在尝试将另一列添加到名为 Year 的数据集中,我在其中将 Year in Names Date -1,但出现以下错误:

library(dplyr)
library(lubridate)

stockprices <- stockprices %>%
  mutate(Year = (year('Names Date')) -1 )

Error in `mutate()`:
! Problem while computing `Year = (year("Names Date")) - 1`.
Caused by error in `as.POSIXlt.character()`:
! character string is not in a standard unambiguous format
Run `rlang::last_error()` to see where the error occurred.

我已经多次使用此代码添加 Year 列,但从未收到此错误,所以我不知道该怎么做。我尝试在 Excel 中更改它的格式,但没有任何帮助。

【问题讨论】:

  • 第一列看起来是一个字符串而不是 Date 对象。在调用 year() 函数之前验证该列是否为 Date 对象。
  • 您似乎在尝试使用无效的列名(它们中不能有空格),并在文本字符串上调用 year。正如您正在尝试获取字符串“Names Date”的年份一样。您确定这是您以前使用过的代码吗?

标签: r lubridate


【解决方案1】:

我做了几件事。正如 camille 指出的那样,你不能在列名中使用空格,所以我修复了它,然后我使用 as.date 将日期列转换为日期类型,最后我去掉了 mutate 命令中的引号,因为变量不必在 dplyr 命令中引用(引号所做的是让 R 认为您想在引用的字符串而不是变量上运行年份)。

stockprices <- data.frame (NamesDate  = c("1985-05-31", "1985-05-31"),
                        TickerSymbol = c("AMFD", "AMT"),
                        Price = c(5.875, 14.375)

stockprices$NamesDate <- as.Date(stockprices$NamesDate)
stockprices <- stockprices %>%
mutate(Year = (lubridate::year(NamesDate)) -1 )

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2021-06-18
    • 2014-05-30
    • 2019-05-17
    相关资源
    最近更新 更多