简体   繁体   中英

Extracting year from dates in a column

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!

If you have a dataset called crimedata and use df instead (when df is not defined as a variable, ie "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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM