3

如果我想将字符串转换为 POSIXlt 会出现问题,但我无法弄清楚问题所在。

df<-data.frame(a=c("2013-07-01 11:51:03" ,"2013-07-01 12:01:50", "2013-07-01 12:05:13"),b=1:3)
#factor(df[,"a"])
df[,"a"]<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")

> Warning message:
In `[<-.data.frame`(`*tmp*`, , "a", value = list(sec = c(3, 50,  :
9 variables declared, to replace 1 variablen

df<-data.frame(a=c("2013-07-01 11:51:03" ,"2013-07-01 12:01:50", "2013-07-01 12:05:13"),b=1:3)
df$a<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
factor(df[,"a"])
> Error in sort.list(y) : 'x' should be atomar for 'sort.list'

直到现在我使用了一个解决方法

a<-as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")
df1<-data.frame(a,df[,"b"])
4

2 回答 2

5

我建议使用 POSIXct:

df[,"a"]<-as.POSIXct(as.character(df[,"a"]),tz="GMT")

如果您必须使用 POSIXlt(为什么?):

df$a <- as.POSIXlt(as.character(df[,"a"]),tz="GMT")

问题是类POSIXlt的对象实际上是列表。$<-可以正确处理,[<-不能。

于 2013-09-16T08:41:42.350 回答
3

POSIXlt将所有内容存储为列表,这会让您感到困惑....

x <- as.POSIXlt(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")

attributes( x[1] )
$names
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"

$class
[1] "POSIXlt" "POSIXt" 

$tzone
[1] "GMT"

#  See how the list is of the first element is of length 9? Hence the error:
unlist(x[1])
#  sec   min  hour  mday   mon  year  wday  yday isdst 
#    3    51    11     1     6   113     1   181     0 

#  POSIXct doesn't do this....
y <- as.POSIXct(as.character(df[,"a"]),origin = "1960-01-01",tz="GMT")

attributes( y[1] )
$class
[1] "POSIXct" "POSIXt" 

$tzone
[1] "GMT"

#  Stores the date/time as a single element
unlist( y[1] )
#[1] "2013-07-01 11:51:03 GMT"
于 2013-09-16T08:45:50.900 回答