为什么 R 在将字符转换为日期时添加额外的行

Why is R adding an extra row when converting characters to dates

我正在使用 strptime.

将字符数据类型的向量转换为 R 中的日期数据类型

当我使用 sapply 检查转换后的数据类型时,它给了我一个额外的行。

下面的最小示例:

test_dates = c("2020-10-01","2019-08-09","2018-07-01")
sapply(test_dates,class)
2020-10-01  2019-08-09  2018-07-01 
"character" "character" "character" 

test_dates = strptime(test_dates, "%Y-%m-%d")
sapply(test_dates,class)
     [,1]      [,2]      [,3]     
[1,] "POSIXlt" "POSIXlt" "POSIXlt"
[2,] "POSIXt"  "POSIXt"  "POSIXt" 

最后第二行是我不确定的地方。不知道是对sapply的误解,还是与R如何存储times/dates有关。如下图,第二行数据什么都没有

test_dates[1][1]
[1] "2020-10-01 BST"
test_dates[1][2]
[1] NA

在此先感谢您的帮助。

您可以使用 lubridate 包(ymd 函数)轻松地将此向量转换为日期。类似的东西:

test_dates <- c("2020-10-01","2019-08-09","2018-07-01")
new_dates <- lubridate::ymd(test_dates)
class(new_dates)

希望对你有帮助:D

R 对象可以有多个 class。您看到的第二行是因为 strptime returns 对象有两个 class,即 POSIXltPOSIXt。当您使用 sapply 时,它会将数据简化为一个可能令人困惑的矩阵。

也许 lapply 的输出不会那么混乱。

lapply(test_dates, class)

#[[1]]
#[1] "POSIXlt" "POSIXt" 

#[[2]]
#[1] "POSIXlt" "POSIXt" 

#[[3]]
#[1] "POSIXlt" "POSIXt" 

此外,一个向量只能有一个 class,因此您可以检查整个向量的 class 而不是每个单独的元素,因为它无论如何都会 return 相同的值。

class(test_dates)
#[1] "POSIXlt" "POSIXt" 

我们也可以用map

library(purrr)
map(test_dates, class)