Reputation: 7424
I want to convert a column of a dataframe in R into a new column with a string format and extract for example only the day or the month. The format of the dataframe could look like this, where the date has already the type Date:
Name,Date,Salary
Bob,12/31/18,1000
Alice,10/28/18,100
John,05/06/17,200
So the target df should look like this:
Name,Date,Day,Month,Salary
Bob,12/31/18,31,12,1000
Alice,10/28/18,28,10,100
John,05/06/17,06,05,200
Upvotes: 1
Views: 576
Reputation: 270428
Use format
. The [...]
part at the end can be omitted if the order of columns is not important.
transform(DF, Day = format(Date, "%d"), Month = format(Date, "%m"))[
c("Name", "Date", "Day", "Month", "Salary")]
giving:
Name Date Day Month Salary
1 Bob 2018-12-31 31 12 1000
2 Alice 2018-10-28 28 10 100
3 John 2017-05-06 06 05 200
There is also some question of whether you really need to add Day and Month columns in the first place given that the Date is already a column. It might be more convenient to extract it on the fly when you need it depending on what you are doing with it.
The input in reproducible form is assumed to be:
Lines <- "Name,Date,Salary
Bob,12/31/18,1000
Alice,10/28/18,100
John,05/06/17,200"
DF <- read.csv(text = Lines)
DF$Date <- as.Date(DF$Date, "%m/%d/%y")
Upvotes: 2
Reputation: 522797
For a base R solution, we can try using first as.Date
to convert your string dates to bona fide R dates. Then, we can convert those dates to POSIXlt objects, in order to extract the day and month components.
x <- "12/31/18"
date <- as.Date(x, "%m/%d/%y")
day <- as.POSIXlt(date)$yday + 1
month <- as.POSIXlt(date)$mon + 1
day
month
[1] 365
[1] 12
Upvotes: 2