I am new to R, but need to know how to separate one column labeled "dates" into three separate columns of, month, year, and date.
There are many ways of doing it, but it's going to depend on the format of your dates, see this example.
# Sample data df <- data.frame(stringsAsFactors = FALSE, dates = c("2019-06-09", "2019-06-10") ) library(tidyverse) df #> dates #> 1 2019-06-09 #> 2 2019-06-10 df %>% separate(dates, c("month", "year", "day"), sep = "-") #> month year day #> 1 2019 06 09 #> 2 2019 06 10
Created on 2019-06-10 by the reprex package (v0.3.0)
I like to use the
lubridate package which is also part of
library(tidyverse) library(lubridate) df <- tibble(dates=c("2019-06-09", "2019-06-10")) # dates as strings df %>% mutate( dates2=ymd(dates), # convert to Date type using lubridate year=year(dates2), # extract parts month=month(dates2), day=day(dates2) ) #> # A tibble: 2 x 5 #> dates dates2 year month day #> <chr> <date> <dbl> <dbl> <int> #> 1 2019-06-09 2019-06-09 2019 6 9 #> 2 2019-06-10 2019-06-10 2019 6 10
Created on 2019-06-11 by the reprex package (v0.3.0)
Instead of specific dates could I do a specific column for example dates=[, 2]?
I don`t understand what you mean with specific dates, I'm using some made up sample data you have to replace this with your own data.
I figured it out, thanks!
If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).
Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.