0

I have a list of dates, for example "1989-10-09" which are characters and I'm trying to organize them by month. By problem is that these are characters and it's difficult to extract just the month from the dates. Right now I'm trying this:

a = as.list(strsplit(official$date[i],split='-'))

Where official is the data frame with a date column. But the result is a list of length one, containing "1989" "10" "09" as a single input with no dimensions. The exact result looks like:

[[1]]
[1] "1959" "10"   "05"  

If I try a[2] I get NULL

Johnny
  • 59
  • 5
  • It is recommended to convert the date strings into a Date object with the `as.Date()` function, then you could select the extract out the month part with `format(*mydateobject*, "%m")` function. – Dave2e Sep 30 '22 at 21:14
  • Try: `a[[1]][2]`. This is how a list can be subsetted. – TarJae Sep 30 '22 at 21:26
  • @dave2e thanks, that worked. How would I format out the year? I tried format(*mydateobject*, "%y") and that gave me the last two digits in the year but not all 4. – Johnny Oct 01 '22 at 01:52
  • For four years use “%Y”. See help for “strptime “ for the list of all the formatting options. – Dave2e Oct 01 '22 at 02:25

1 Answers1

0

If this is the way you want to go about doing it, you would first need to unlist the item:

my_list <- list(1:3)
#>[[1]]
#>[1] 1 2 3

my_list[2]
#> NULL

unlist(my_list)[2]
#>[1] 2

Though as @Dave2e mentioned, it might be best to convert it to a date and use more syntactically rich verbs (maybe like lubridate::month)

Kai Aragaki
  • 377
  • 3
  • 13