Victor Maxwell
Victor Maxwell

Reputation: 314

Apply strptime to data.frame

I have a data.frame object which contains separate columns for year, month, and day. i want to convert this into one column of POSIXlt type objects. so my data.frame look like

test_df <- data.frame(matrix(data = as.integer(c(1900,1900,1900,1,1,1,1,2,3)), 
                             nrow = 3, ncol = 3))
colnames(test_df) <- c("Year","Month","Day")

if i try to convert an individual row in the following manner

paste(test_df$Year[1], test_df$Month[1], test_df$Day[1], sep = "/") %>%
as.factor() %>% 
strptime(format = "%Y/%m/%d")

i end up with a POSIXlt class object. however if i try to use an apply function such as this

test_df$date <- apply(test_df, 1, 
                      function(x) 
                      strptime(as.factor(paste(x[1], x[2], x[3], 
                                         sep = "/")), 
                               format = "%Y/%m/%d"))

i end up getting list objects in that new column. What can i do to maintain the POSIXlt class while using apply?

Upvotes: 0

Views: 955

Answers (1)

ozanstats
ozanstats

Reputation: 2864

It is better practice to use POSIXct instead of POSIXlt in data frames. The following should do the same job:

library(dplyr)

df <- test_df %>%
  mutate(date = as.POSIXct(paste(Year, Month, Day), format = "%Y %m %d"))

str(df)
# 'data.frame': 3 obs. of  4 variables:
#   $ Year : int  1900 1900 1900
# $ Month: int  1 1 1
# $ Day  : int  1 2 3
# $ date : POSIXct, format: "1900-01-01" "1900-01-02" "1900-01-03"

Upvotes: 1

Related Questions