0

I have a data frame called "div" where the "started_date" column (corresponds to the 3rd column) has a character format like "yyyy-mm-dd".

I formatted all the entries in this column to set everything as dates in the following way:

div$started_date<-ymd(div$started_date)

So my question is: if I try to determine the year for the first entry like year(div$started_date[1]) it prints the year, though if I use year(div[1,3]) the following message is printed in the console:

Error in as.POSIXlt.default(x, tz = tz(x)) : 
  do not know how to convert 'x' to class “POSIXlt”

Your help is much appreciated.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Miguel_s
  • 79
  • 3
  • 2
    Welcome to SO! To help us to help you would you mind sharing [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Feb 09 '22 at 18:48
  • 1
    ... this said: I just tried on a simple dataset `div <- data.frame(x = 1, y = 1, started_date = "2022-02-09")`. And both approaches you mentioned worked fine. – stefan Feb 09 '22 at 18:51
  • 1
    What is `class(div)` and `class(div[1,3])`? As already mentioned you need to include data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we can actually run the code to see what's going on. We can't tell anything about how your data is encoded at the moment. – MrFlick Feb 09 '22 at 18:51
  • Thank you for your reply. I have just tried both class(div) and class(div[1,3]) as you said and I got the following: "tbl_df" "tbl" "data.frame". I guess there's a problem somewhere here... It should output date I guess. – Miguel_s Feb 09 '22 at 19:04
  • I just noticed that if on the other hand I call class(div$started_date) it outputs "date" as expected. – Miguel_s Feb 09 '22 at 19:07
  • 1
    That implies you are using a tibble, when you subset a tibble with `[]` you will always get a tibble back. This is different than how a data.frame works. You can try `year(div[1,3, drop=TRUE])` if you really need to subset that way – MrFlick Feb 09 '22 at 19:07
  • That works perfectly! Thank you very much. By the way, is there any other way you recommend doing this then without using the square brackets? – Miguel_s Feb 09 '22 at 19:14
  • 2
    Depending on what you are trying to do, you might use dplyr to get the result you want. But it's hard to tell from the information you have posted here – user3124634 Feb 09 '22 at 21:04

0 Answers0