akang
akang

Reputation: 651

Print a specific element from a list in R

I have a list like below

dput(mylist)
structure(list(Var1 = structure(1:27, .Label = c("01-2018", "01-2019", 
"02-2020", "03-2019", "03-2020", "04-2018", "04-2019", "04-2020", 
"05-2017", "05-2018", "05-2019", "05-2020", "06-2019", "06-2020", 
"07-2019", "07-2020", "08-2019", "08-2020", "09-2019", "09-2020", 
"10-2016", "10-2017", "10-2019", "11-2018", "11-2020", "12-2018", 
"12-2019"), class = "factor"), Freq = c(1L, 1L, 2L, 1L, 3L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 4L, 1L, 1L, 1L, 2L, 2L, 1L, 
2L, 1L, 1L, 1L, 3L)), class = "data.frame", row.names = c(NA, 
-27L))

I am trying to extract the most recent date and print it out like below but doesn't work

test<-mylist %>% slice(which.max(as.Date(Var1, '%m-%Y')))
print(paste(c("month is", test[1], "number is", test[2]), collapse = " ")))

Desired output :

month is 11-2020, number is 1

OR

month is November,2020, number is 1

Upvotes: 1

Views: 274

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388817

Here is a base R option :

inds <- which.max(as.Date(paste0('01-', mylist$Var1), '%d-%m-%Y'))
sprintf('month is %s, number is %d', mylist$Var1[inds], mylist$Freq[inds])
#[1] "month is 11-2020, number is 1"

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Here is a data.table option

setDT(mylist)[
  which.max(as.IDate(paste0("01-", Var1), format = "%d-%m-%Y"))
][
  ,
  sprintf("month is %s, number is %d", Var1, Freq)
]

giving

[1] "month is 11-2020, number is 1"

Upvotes: 0

akrun
akrun

Reputation: 886948

The issue is that Date class requires a day as well. We can use yearmon class for sliceing the rows with the max value of 'Var1'

library(dplyr)
test <- mylist %>%
         slice(which.max(zoo::as.yearmon(Var1, "%m-%Y")))
         # // or use slice_max
         #slice_max(zoo::as.yearmon(Var1, "%m-%Y"))

sprintf("month is %s, number is %d", test$Var1, test$Freq)
#[1] "month is 11-2020, number is 1"

Or another option is with glue

library(stringr)
mylist %>%
    mutate(Var1 = as.Date(str_c(Var1, '-01'), "%m-%Y-%d")) %>%
    slice_max(Var1) %>% 
    glue::glue_data("month is {format(Var1, '%m-%Y')}, number is {Freq}") %>%
    as.character
#[1] "month is 11-2020, number is 1"

mylist %>%
   mutate(Var1 = as.Date(str_c(Var1, '-01'), "%m-%Y-%d")) %>% 
   slice_max(Var1) %>%
   glue::glue_data("month is {format(Var1, '%B,%Y')}, number is {Freq}") %>%
   as.character
#[1] "month is November,2020, number is 1"

Upvotes: 1

Related Questions