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')
but I get the error:
provided 9 variables to replace 1 variables
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?
This is due to the result of
strptime()being an object of class"POSIXlt":A
"POSIXlt"object is a list representation (hence theltrather than thectin the class name) of the time:A
"POSIXlt"object is a list of length 9: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:but we are still loosing the class information. Still, you can go back to the
"POSIXct"representation later using theas.POSIXct()function but you will need to specify theoriginargument. See?POSIXctfor more.A solution is to coerce
ps$X1to be class"POSIXct"before inserting the time: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.