2014-01-23 17 views
3

下面是示出該問題的可再現例如:從數據幀變換爲數據表獲得帶有頭部(..)的誤差

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 

以下是錯誤在執行頭(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]) 

預先感謝您

回答

5

這是一個迷人的錯誤造成的具體日期,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對象的基礎列表/矢量性質。

+2

目前POSIXlt列不受'data.table'支持(請參閱[這裏](http://stackoverflow.com/a/14063077/1385941))。 – mnel

+1

@mnel它似乎應該錯誤,然後,不是?感謝您的鏈接,我沒有意識到(儘管我從來沒有需要使用'POSIXlt'。 – BrodieG