Set time value in data frame cell

I am trying to set the time value to a data frame:

ps = data.frame(t(rep(NA, 2))) ps[1,1] = strptime('10:30:00', '%H:%M:%S') 

but I get the error:

 provided 9 variables to replace 1 variables 

since the time value is a list (?) in R, it thinks I'm trying to set 9 columns when I just want to set one column for this class.

What can I do to do it right?

+4
source share
1 answer

This is because the result of strptime() is 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" object is a list view (hence lt , not ct in the class name) of 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" object is a list of lengths 9:

 > length(unclass(foo)) [1] 9 

therefore, a warning message, as the object is discarded back to its component parts / view. Instead, you can embed the "POSIXct" without generating a warning:

 > ps[1,1] = as.POSIXct(strptime('10:30:00', '%H:%M:%S')) > ps[1,1] [1] 1332325800 

but we are still losing class information. However, you can return to the "POSIXct" later using the as.POSIXct() function, but you need to specify the origin argument. See ?POSIXct more details.

 > class(ps[1,1]) [1] "numeric" 

The solution is to force ps$X1 to the "POSIXct" class before "POSIXct" 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 

Without warning (as before with as.POSIXct() ), but also information about the class is saved, where before its loss. Read ?`[.data.frame` , especially the ?`[.data.frame` section, which has some details; but I understand how understanding what coercion is in such substitutions is difficult.

+9
source

Source: https://habr.com/ru/post/1402662/


All Articles