Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract only year from the date in dataframes? [duplicate]

Tags:

r

This is my data...& i need to extract data by using only basic R(dont use mysql, php,python ,c# or any other)

**service**        **Date**
disconnected        2013-01-14
disconnected        2013-03-15
disconnected        2012-02-24
disconnected        2012-12-05
disconnected        2012-06-08
disconnected        2011-05-08 
disconnected        2010-10-11 
disconnected        2010-12-02

The data i need to extract is only year...from the date....& later again i need to assign it to new variable or vector.....

the following output should be....

OUTPUT
**service**        **Date**
disconnected        2013
disconnected        2013
disconnected        2012
disconnected        2012
disconnected        2012
disconnected        2011 
disconnected        2010 
disconnected        2010
like image 674
arshia Avatar asked Feb 08 '23 17:02

arshia


1 Answers

There are many options. One way is using substr to get the first 4 character elements from 'Date' column (assuming that we are not going back to > 1000 )

 df1$Year <- substr(df1$Date, 1,4)

Or we match the substring that begins from - followed by one or more characters to the end of the string, replace with '' using sub.

df1$Year <- sub('-.*$', '', df1$Date)

Or we can extract the year by converting to POSIXlt class

 strptime(df1$Date, '%Y-%m-%d')$year+1900

If we are allowed to use packages, library(lubridate) has a convenient function i.e. year

library(lubridate)
year(df1$Date)

data

df1 <- structure(list(service = c("disconnected", "disconnected", "disconnected", 
"disconnected", "disconnected", "disconnected", "disconnected", 
"disconnected"), Date = c("2013-01-14", "2013-03-15", "2012-02-24", 
"2012-12-05", "2012-06-08", "2011-05-08", "2010-10-11", "2010-12-02"
)), .Names = c("service", "Date"), class = "data.frame",
row.names = c(NA, -8L))
like image 76
akrun Avatar answered Feb 11 '23 08:02

akrun