Reputation: 69
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!
Upvotes: 0
Views: 9329
Reputation: 6813
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"))
Upvotes: 4