gpt4 book ai didi

r - 从数据框转换为数据表时,head(..) 出现错误

转载 作者:行者123 更新时间:2023-12-01 11:40:32 28 4
gpt4 key购买 nike

下面是一个显示问题的可重现示例:

openSummary <- read.table(textConnection(
"Dates dollarA numTotal
7/3/2011 52730.56 1614
7/10/2011 77709.43 1548"), header = TRUE)
openSummary$Dates <- strptime(openSummary$Dates,"%m/%d/%Y")
str(openSummary)
head(openSummary) # No problem

openSummaryDT <- data.table(openSummary)
str(openSummaryDT)
head(openSummaryDT) # An error is produced

这是执行 head(openSummaryDT) 时的错误

Error in `rownames<-`(`*tmp*`, value = paste(format(rn, right = TRUE),  : 
length of 'dimnames' [1] not equal to array extent

请解释错误以及如何避免它。但是,我似乎可以对数据框和数据表进行一些操作,并且得到相同的结果。

difftime(Sys.Date(), openSummary[ ,"Dates"])
difftime(Sys.Date(), openSummaryDT[ ,Dates])

提前致谢

最佳答案

这是一个令人着迷的错误,由 POSIXlt 格式的日期引起。考虑:

openSummary$Dates <- as.Date(openSummary$Dates)
head(data.table(openSummary))
# Dates dollarA numTotal
# 1: 2011-07-03 52730.56 1614
# 2: 2011-07-10 77709.43 1548

如果您尝试打印原始表,您会遇到同样的错误,但通过追溯,您会看到:

> openSummaryDT
# Error in `rownames<-`(`*tmp*`, value = paste(format(rn, right = TRUE), :
# length of 'dimnames' [1] not equal to array extent
# In addition: Warning message:
# In cbind...
# Enter a frame number, or 0 to exit
# 1: print(list(Dates = list(sec = c(0, 0), min = c(0, 0), hour = c(0, 0), m
# 2: print.data.table(list(Dates = list(sec = c(0, 0), min = c(0, 0), hour =
# 3: `rownames<-`(`*tmp*`, value = paste(format(rn, right = TRUE), ":", sep
> 3
# Called from: print.data.table(list(Dates = list(sec
Browse[1]> ls()
# [1] "dn" "value" "x"
Browse[1]> x
# Dates dollarA numTotal
# sec "0,0" "52730.56" "1614"
# min "0,0" "77709.43" "1548"
# hour "0,0" "52730.56" "1614"
# mday "3,10" "77709.43" "1548"
# mon "6,6" "52730.56" "1614"
# year "111,111" "77709.43" "1548"
# wday "0,0" "52730.56" "1614"
# yday "183,190" "77709.43" "1548"
# isdst "1,1" "52730.56" "1614"

基本上,无论出于何种原因,将 data.table 转换为用于打印/标题的文本形式的过程暴露了 POSIXlt 对象的底层列表/向量性质。

关于r - 从数据框转换为数据表时,head(..) 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21320215/

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