将时间值设置为数据帧单元 [英] Set time value into data frame cell
问题描述
我正在尝试将时间值设置为数据框:
I'm trying to set a time value into a data frame:
ps = data.frame(t(rep(NA, 2)))
ps[1,1] = strptime('10:30:00', '%H:%M:%S')
但我收到错误:
provided 9 variables to replace 1 variables
由于时间值是R中的列表(?),它认为我'我试图设置9列,当我真的只想设置一个列到该类。
since a time value is a list (?) in R it thinks I'm trying to set 9 columns, when I really just want to set the one column to that class.
我可以做什么来使这个设置正确?
What can I do to make this set properly?
推荐答案
这是由于 strptime()
的结果是一个类POSIXlt
:
This is due to the result of strptime()
being an object of class "POSIXlt"
:
> ps = data.frame(t(rep(NA, 2)))
> ps[1,1] = strptime('10:30:00', '%H:%M:%S')
Warning message:
In `[<-.data.frame`(`*tmp*`, 1, 1, value = list(sec = 0, min = 30L, :
provided 9 variables to replace 1 variables
> strptime('10:30:00', '%H:%M:%S')
[1] "2012-03-21 10:30:00"
> class(strptime('10:30:00', '%H:%M:%S'))
[1] "POSIXlt" "POSIXt"
A POSIXlt
对象是列表表示(因此 lt
而不是
A "POSIXlt"
object is a list representation (hence the lt
rather than the ct
in the class name) of the time:
> foo <- strptime('10:30:00', '%H:%M:%S')
> str(foo)
POSIXlt[1:1], format: "2012-03-21 10:30:00"
> unclass(foo)
$sec
[1] 0
$min
[1] 30
$hour
[1] 10
$mday
[1] 21
$mon
[1] 2
$year
[1] 112
$wday
[1] 3
$yday
[1] 80
$isdst
[1] 0
A POSIXlt
对象是长度为9的列表:
A "POSIXlt"
object is a list of length 9:
> length(unclass(foo))
[1] 9
因此,警告消息该对象正在被剥离回它的组成部分/表示。您可以使用POSIXct
代替,而不会生成警告:
hence the warning message, as the object is being stripped back to it's constituent parts/representation. You can stick the "POSIXct"
representation in instead without generating the warning:
> ps[1,1] = as.POSIXct(strptime('10:30:00', '%H:%M:%S'))
> ps[1,1]
[1] 1332325800
但是我们还是放弃了信息。不过,您可以稍后使用 as.POSIXct()
函数返回POSIXct
表示,但是您将需要指定 origin
参数。请参阅?POSIXct
了解更多信息。
but we are still loosing the class information. Still, you can go back to the "POSIXct"
representation later using the as.POSIXct()
function but you will need to specify the origin
argument. See ?POSIXct
for more.
> class(ps[1,1])
[1] "numeric"
将 ps $ X1
加入POSIXct
之前插入时间:
A solution is to coerce ps$X1
to be class "POSIXct"
before inserting the time:
> ps = data.frame(t(rep(NA, 2)))
> ps <- transform(ps, X1 = as.POSIXct(X1))
> ps[1,1] <- as.POSIXct(strptime('10:30:00', '%H:%M:%S'))
> ps
X1 X2
1 2012-03-21 10:30:00 NA
> str(ps)
'data.frame': 1 obs. of 2 variables:
$ X1: POSIXct, format: "2012-03-21 10:30:00"
$ X2: logi NA
没有警告(与以前一样的 as.POSIXct()
),而且还保留了类信息,失去了请阅读?[.data.frame`
,特别是具有一些细节的强制部分;但是,我的看法是如何理解这样的替代的强制是棘手的。
No warning (as before with as.POSIXct()
) but also the class information is retained, where before it was lost. Do read ?`[.data.frame`
, especially the Coercion section which has some details; but my take how is that understanding the coercion in replacements like this is tricky.
这篇关于将时间值设置为数据帧单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!