如果我想将字符串转换为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"])
答案 0 :(得分:5)
我建议使用POSIXct:
df[,"a"]<-as.POSIXct(as.character(df[,"a"]),tz="GMT")
如果你必须使用POSIXlt(为什么?):
df$a <- as.POSIXlt(as.character(df[,"a"]),tz="GMT")
问题是类POSIXlt
的对象实际上是列表。 $<-
可以正确处理,[<-
不能。
答案 1 :(得分: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"