pepece
pepece

Reputation: 370

apply making conversion (POSIXct)

I was using apply on a data.frame with POSIXct objects. The problem is that apply begins with converting the input data.frame as.matrix() (according to what I read). Which means that POSIXct will then be casted to char.

I solve my issue by using lapply instead. However is there some better solutions?

    # data.frame with one column of posixct
    pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
    str(pos) # POSIXct

    test = function(x){
      str(x[1])
      return(x)
    }                 
    res = data.frame(apply(pos, 2, test))
    str(res) # all strings

    res2 = data.frame(lapply(pos, test))
    str(res2) # all POSIXct

Upvotes: 2

Views: 53

Answers (1)

see24
see24

Reputation: 1210

You could use the map_df function from the purrr package. The map function has different versions for different output types so for this case you would use map_df

# data.frame with one column of posixct
pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
str(pos) # POSIXct

test = function(x){
  str(x[1])
  return(x)
}                 
res = data.frame(apply(pos, 2, test))
str(res) # all strings

res2 = data.frame(lapply(pos, test))
str(res2) # all POSIXct

library(purrr)

res3 = map_df(pos, test)
str(res3)

Upvotes: 1

Related Questions