當我分配POSIXct對象到數據幀時,它把它轉換成整數當量,例如:R:分配POSIXct類的數據幀
> x<-as.data.frame(matrix(nrow=1,ncol=2))
> x
V1 V2
1 NA NA
> x[1,1]<-as.POSIXct("2010-12-07 08:00:00")
> x
V1 V2
1 1291708800 NA
是否有一種方法來阻止這種行爲,或者在完成所有任務後輕鬆地將整數轉換回POSIXct?
當我分配POSIXct對象到數據幀時,它把它轉換成整數當量,例如:R:分配POSIXct類的數據幀
> x<-as.data.frame(matrix(nrow=1,ncol=2))
> x
V1 V2
1 NA NA
> x[1,1]<-as.POSIXct("2010-12-07 08:00:00")
> x
V1 V2
1 1291708800 NA
是否有一種方法來阻止這種行爲,或者在完成所有任務後輕鬆地將整數轉換回POSIXct?
您需要在創建完成後轉換該列。
x <- as.data.frame(matrix(nrow=1,ncol=2))
class(x[1,1])
[1] "logical"
看看它是如何分配的class
。 A matrix
只能有一種數據類型。
x[,1] <- as.POSIXct(x[,1])
x[1,1] <- as.POSIXct("2010-12-07 08:00:00")
class(x[1,1])
[1] "POSIXt" "POSIXct"
x
V1 V2
1 2010-12-07 08:00:00 NA
當然,我不清楚爲什麼你將它創建爲一個空矩陣開始。你可以輕鬆完成:
x <- data.frame(date=as.POSIXct("2010-12-07 08:00:00"), value=NA)
我有完全相同的問題。爲了解決這個問題,我使用as.POSIXct()
來聲明數據框的列類。
例子:
> temp = data.frame(col1 = NA)
> temp[1,] = Sys.time()
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: num 1.4e+09
但
> temp = data.frame(col1 = as.POSIXct(NA,""))
> temp[1,] = Sys.time()
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: POSIXct, format: "2014-05-21 15:35:46"
有趣的是,即使最初的默認列類是"logical"
:
> temp = data.frame(col1 = NA)
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: logi NA
你可以把字符寫入到它:
> temp = data.frame(col1 = NA)
> temp[1,] = "hello"
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: chr "hello"
然而,像POSIXct
,你可以不寫的因素:
> temp = data.frame(col1 = NA)
> temp[1,] = as.factor("hello")
> str(temp)
'data.frame': 1 obs. of 1 variable:
$ col1: int 1
另外要注意,'編輯()'和'修復()'將從變量剝離Date類,並將其轉換爲字符(在至少在R 2.12.0中)。爲什麼這是我不知道的。 – caracal 2010-12-17 15:46:07
你明星。謝謝! – 2010-12-17 15:50:54
當我使用這個解決方案時,我不得不將原點和時區添加到命令中。 – userJT 2012-04-16 19:15:18