出现错误“要替换的项目数不是替换长度的倍数”

问题描述 投票:7回答:1

我正在尝试使用strptime函数将记录转换为日期和时间格式。但是,我不确定为什么会出现错误:

要替换的项目数不是替换长度的倍数。

我尝试使用length函数检查记录的长度,但是两者的长度相同。

data <- DT
head(data[6])
#                column
# 1 2014-12-22 23:53:48
# 2 2014-12-22 23:20:34
# 3 2014-12-22 23:20:30
# 4 2014-12-22 23:20:16
# 5 2014-12-22 23:20:07
# 6 2014-12-22 23:05:49

data[,6] <- as.character(data[,6])

temp_file <- matrix(0,nrow=nrow(data))

temp_file[1] <- strptime(data[1, 6],"%F %T")
# Warning message:
# In temp_file[1] <- strptime(data[1, 6], "%F %T") :
#   number of items to replace is not a multiple of replacement length

length(temp_file[1])
# [1] 1

length(data[1,6])
# [1] 1

length(strptime(data[1, 6], "%F %T") )
# [1] 1

非常感谢您的帮助。

谢谢!

r dataframe matrix strptime
1个回答
0
投票

您可以使用ymd_hms程序包的lubridate功能将字符向量转换为日期时间格式:

library(lubridate)

# data frame simulation
structure(list(X1 = c(1, 1, 1, 1, 1, 1), X1.1 = c(1, 1, 1, 1, 1, 1), 
    X1.2 = c(1, 1, 1, 1, 1, 1), X1.3 = c(1, 1, 1, 1, 1, 1), 
    X1.4 = c(1, 1, 1, 1, 1, 1), date_time_char = c("2014-12-22 23:53:48", 
    "2014-12-22 23:20:34", "2014-12-22 23:20:30", "2014-12-22 23:20:16", 
    "2014-12-22 23:20:07", "2014-12-22 23:05:49")), class = "data.frame", row.names = c(NA, -6L))

# transform from character to datetime
data$date_time <- ymd_hms(data[, 6])
data[, 7]

输出:

[1] "2014-12-22 23:53:48 UTC" "2014-12-22 23:20:34 UTC" "2014-12-22 23:20:30 UTC" "2014-12-22 23:20:16 UTC"
[5] "2014-12-22 23:20:07 UTC" "2014-12-22 23:05:49 UTC"

N.B。 David Arenburg的评论非常好:

这实际上是一个好问题。这不是错误,而是警告,但您得到的结果是错误的,因此您可以将其视为一个错误。发生这种情况的原因是由于R中的一个矩阵,该矩阵只能获得原子向量。当你尝试将strptime传递给矩阵,它的类是“ POSIXlt”“ POSIXt”,因此它对其进行取消分类,并因此返回其属性列表(长度大于1),即unclass(s​​trptime(data [1,1],“%F%T”))。第一个值是48秒。这正是您所拥有的temp_file [1]现在。

© www.soinside.com 2019 - 2024. All rights reserved.