Coogan Pillay
Coogan Pillay

Reputation: 37

Timestamp in R Studio

n R studio how do you Convert the timestamp column to dates using the lubridate::as_datetime function?

data(movielens)
library(dslabs)

timestamp

(Header)
(1) 1260759144 
(2) 1260759179 
(3) 1260759182 
(4) 1260759185

Trying to convert the (epoch time). to Proper date with time.

data(movielens)
lubridate as_datetime

2019-04-29 08:01

Upvotes: 1

Views: 2354

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388962

Using only dplyr and base R functions from time-manipulations we can convert the timestamp to POSIXct object, extract the year from it and count number of reviews for each year and arrange it in decreasing order.

library(dplyr)
library(dslabs)
data(movielens)

movielens %>%
   mutate(timestamp1 = as.POSIXct(timestamp, origin = "1970-01-01", tz = "UTC"), 
          year = format(timestamp1, "%Y")) %>%
   count(year) %>%
   arrange(desc(n))


# A tibble: 22 x 2
#   year      n
#   <chr> <int>
# 1 2000  13869
# 2 2006   7493
# 3 2005   7161
# 4 2015   6610
# 5 1996   6239
# 6 2016   6225
# 7 1999   5901
# 8 2001   4658
# 9 2004   4658
#10 2003   4462
# … with 12 more rows

Or using lubridate functions

library(lubridate)
movielens %>%
   mutate(timestamp1 = as_datetime(timestamp),
          year = year(timestamp1)) %>%
   group_by(year) %>%
   summarise(n = n()) %>%
   arrange(desc(n))

Upvotes: 1

Related Questions