0

I have a dataset called verts imported from Excel with a column called Date that contains dates in this format: m/d/yyyy. I'm trying to extract the year from this column.

Here's what I'm currently trying:

verts$Date_converted <- strptime(verts$Date, format = "%m-%d-%y")   
verts$Year <- format(verts$Date_converted, "%y")

This produced two new columns in R, as you can see in the image, but both columns only contain NA.

my excel data in R with the two new columns I tried to convert to "Date" form and filter for year

Any ideas on what I'm doing wrong?

Andrea M
  • 2,314
  • 1
  • 9
  • 27
  • Your date contains "/" and not "-" also you have a 4 digit year thus "%Y". `format = "%m/%d/%Y"` – Dave2e Apr 13 '22 at 21:50
  • I will try that, thank you so much. Very much a beginner at this. – Nutmeg25 Apr 13 '22 at 22:31
  • That worked!! Many thanks. Any suggestions on how to go about nesting the grouping I need to do between characters and the numeric year? I know how to group just those two but I am struggling to filter out just Caudata from the Order column. – Nutmeg25 Apr 14 '22 at 01:19
  • 1
    There are plenty of similar questions here to search for. See the group_by function in the dplyr package, that could be a good starting point. – Dave2e Apr 14 '22 at 01:22
  • dplyr is what I was starting to play with so I'll continue down that path - thanks again! – Nutmeg25 Apr 14 '22 at 02:17

1 Answers1

0

I recommend using package lubridate for dates - it makes everything so much easier.

  • mdy() quickly parses a date that's written in the US format - regardless of delimiter type.
  • year() extracts the year from an object in date format.
verts <- data.frame(Date = c("6/8/2004", "6/14/2004", "7/7/2006"))

verts <- verts |> 
  dplyr::mutate(Date_converted = lubridate::mdy(Date),
                year = lubridate::year(Date_converted))

verts
#>        Date Date_converted year
#> 1  6/8/2004     2004-06-08 2004
#> 2 6/14/2004     2004-06-14 2004
#> 3  7/7/2006     2006-07-07 2006

Created on 2022-04-22 by the reprex package (v2.0.1)

PS please don't use screenshots for data - we can't import that into R. Read here to make it more likely for you to get help.

Andrea M
  • 2,314
  • 1
  • 9
  • 27