gpt4 book ai didi

r - 收到错误 "number of items to replace is not a multiple of replacement length"

转载 作者:行者123 更新时间:2023-12-04 12:58:09 25 4
gpt4 key购买 nike

我正在尝试使用 strptime 将记录转换为日期和时间格式功能。但是,我不确定为什么会收到错误消息:

number of items to replace is not a multiple of replacement length.



我尝试使用 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

任何帮助是极大的赞赏。

谢谢!

最佳答案

您可以使用 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"

注意David Arenburg 的评论非常好:

That is actually a good question. This isn't an error, rather a warning, but the result you get is wrong, so you could consider it as an error. The reason this is happening is because of the definition of a matrix in R, which can only get atomic vectors. When you are trying to pass strptime to the matrix, it's class is "POSIXlt" "POSIXt", thus it is unclasses it and thus returns a list of its attributes (which length is larger than 1), i.e., unclass(strptime(data[1,1],"%F %T")). The first value is 48 seconds. This is exactly what you have in temp_file[1] now.

关于r - 收到错误 "number of items to replace is not a multiple of replacement length",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com