0

I'm really new to R!

I have the following column CMPLNT_FR_DT in a dataset called crimedata

CMPLNT_FR_DT
12/31/2015
01/23/2009
10/04/2010
05/31/2015

I need to change the column values so that the dates only include the years, like:

CMPLNT_FR_DT
2015
2009
2010
2015

I tried solutions from Extract year from date

but my error returns as

format(as.Date(df$CMPLNT_FR_DT, format="%m/%d/%Y"),"%Y")

Error in df$CMPLNT_FR_DT : object of type 'closure' is not subsettable

I'm not sure what I am doing wrong. I would really appreciate your help!

user2554330
  • 30,741
  • 4
  • 34
  • 76
jaewhyun
  • 51
  • 2
  • 9

1 Answers1

4

If you have a dataset called crimedata and use df instead (when df is not defined as a variable, i.e. "df" %in% ls() returns [1] FALSE), you would get the error Error in df$CMPLNT_FR_DT : object of type 'closure' is not subsettable. This is because df() is a function from the stats package (which is why it might not be good practice to use df as a variable name).

If you change it to format(as.Date(crimedata$CMPLNT_FR_DT, format="%m/%d/%Y"),"%Y") it will work.

There is another solution, using the package lubridate, which returns the year as numeric, which might be useful:

library(lubridate)
year(as.Date(crimedata$CMPLNT_FR_DT, format = "%m/%d/%Y"))
clemens
  • 6,224
  • 2
  • 16
  • 27
  • Thanks so much! I now understand what I was doing wrong. Is there any way I could fix the whole column values according to the years in the original dataset? – jaewhyun Nov 06 '17 at 15:16
  • Are you sure? Try `df – Sotos Nov 06 '17 at 15:21
  • i have added a line to further explain my point. of course, if you have a dataframe `df` defined, it would work. However, the error comes from the fact that `df` is not defined. – clemens Nov 06 '17 at 15:35
  • If It is not defined then why would they call it? Doesn't make sense. The way the question is asked shows that the data framed was named `df`. – Sotos Nov 06 '17 at 15:55
  • in the question is says: 'I have the following column CMPLNT_FR_DT in a dataset called crimedata'. – clemens Nov 06 '17 at 15:57
  • With `lubridate` you can also write `year(mdy(crimedata$CMPLNT_FR_DT))` – acylam Nov 06 '17 at 16:19