Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep POSIXct format when appending string to date item in list?

Tags:

r

Here the time is added to list and list converted to string:

str(list(Sys.time()))

Output is :

  POSIXct[1:1], format: "2017-11-10 21:22:56"

How to paste string to list item and keep format ? This should be outputted :

  List of 1
  $ : Time : POSIXct[1:1], format: "2017-11-10 21:22:56"

I've tried :

str(list(paste("time" , Sys.time())))
str(list(c("time" , Sys.time())))

But the outputs are :

> str(list(paste("time" , Sys.time())))
List of 1
$ : chr "time 2017-11-10 21:23:23"
> str(list(c("time" , Sys.time())))
List of 1
$ : chr [1:2] "time" "1510349011.98052"
like image 905
blue-sky Avatar asked Dec 12 '25 06:12

blue-sky


1 Answers

str(list(paste("time" , Sys.time())))

This is a list of length 1, the 1 element is from paste, which is going to return a character string, because that's what pastes job is. So str reports a list of length 1 of chr type.

str(list(c("time" , Sys.time())))

This is also a list of length 1, the 1 element is a vector (created by c) of the string "time" and a POSIXct object from Sys.time(). Vectors can only store one kind of thing, so R has to convert everything to characters.

Interestingly the way POSIXct elements in a vector are converted to chr depends on what's the first element in the vector:

> str(c("this",Sys.time()))
 chr [1:2] "this" "1510353128.84358"

> str(c(Sys.time(),"this"))
 POSIXct[1:2], format: "2017-11-10 22:33:13" NA
 Warning message:
 In as.POSIXlt.POSIXct(x, tz) : NAs introduced by coercion

Because R is using the first element to figure out which conversion method to use. If the first element is a character, it uses as.character.default which converts POSIXt objects to numbers because deep down they are just numbers, and as.character.default doesn't understand POSIXt timestamps:

> as.character.default(Sys.time())
[1] "1510353378.21108"

If the first element, or all the elements, are POSIX objects then you do get a formatted timestamp:

> as.character.POSIXct(Sys.time())
Error in as.character.POSIXct(Sys.time()) : 
  could not find function "as.character.POSIXct"
> as.character.POSIXt(Sys.time())
[1] "2017-11-10 22:36:30"

This fails:

> str(c(Sys.time(),"this"))
 POSIXct[1:2], format: "2017-11-10 22:33:13" NA
 Warning message:
 In as.POSIXlt.POSIXct(x, tz) : NAs introduced by coercion

because its trying to call as.POSIXlt.POSIXct on a string "this":

> as.POSIXlt.POSIXct("this")
[1] NA
Warning message:
In as.POSIXlt.POSIXct("this") : NAs introduced by coercion
> 

Clear? Probably not. Basically you should figure out what you want and format data elements into character before you start pasting strings together.

like image 187
Spacedman Avatar answered Dec 15 '25 05:12

Spacedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!