获取错误"要替换的项目数不是替换长度的倍数"

dix*_*ixi 7 r matrix strptime dataframe

我正在尝试使用该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
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏.

谢谢!

Art*_*tem 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]
Run Code Online (Sandbox Code Playgroud)

输出:

[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"
Run Code Online (Sandbox Code Playgroud)

注:大卫·阿伦堡 (David Arenburg) 的评论非常好:

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