0

Sorry for unclear title. I have data like this;

        date   pr
1 12-24-2019 1.21
2 12-25-2019 0.00
3 12-26-2019 0.00
4 12-27-2019 1.46
5 12-28-2019 0.00
6 12-29-2019 0.00

But I want to convert it to this type;

  year month date time   pr
1 2019    12   24    1 1.21
2 2019    12   25    1 0.00
3 2019    12   26    1 0.00
4 2019    12   27    1 1.46
5 2019    12   28    1 0.00
6 2019    12   29    1 0.00

Here is structure of my data;

data<-structure(list(date = c("12-24-2019", "12-25-2019", "12-26-2019", 
                        "12-27-2019", "12-28-2019", "12-29-2019"), pr = c(1.21, 0, 0, 
                                                                          1.46, 0, 0)), row.names = c(NA, 6L), class = "data.frame")

And the desired output;

out<-structure(list(year = c(2019L, 2019L, 2019L, 2019L, 2019L, 2019L
), month = c(12L, 12L, 12L, 12L, 12L, 12L), date = c(24L, 25L, 26L, 27L, 
                                               28L, 29L), time = c(1L, 1L, 1L, 1L, 1L, 1L), pr = c(1.21, 0, 0, 
                                                                                                 1.46, 0, 0)), row.names = c("1", "2", "3", "4", "5", 
                                                                                                                             "6"), class = "data.frame")

Time will be fixed as 1.

2 Answers2

1

tidyverse solution

library( lubridate )
library( dplyr )

data %>% 
  mutate( date = as.Date( date, format = "%m-%d-%Y" ),
          year = lubridate::year( date ),
          month = lubridate::month( date ),
          day = lubridate::day( date ),
          time = 1 ) %>% 
  select( year, month, day, time, pr )
Wimpel
  • 26,031
  • 1
  • 20
  • 37
1

A mix of tidyverse and base R is next. You can format the date variable and then use separate to create the new variables:

library(tidyverse)
#Code
data %>% mutate(date=as.Date(date,'%m-%d-%Y')) %>%
  separate(date,into = c('year','month','day'),sep = '-') %>%
  mutate(time=1)

Output:

  year month day   pr time
1 2019    12  24 1.21    1
2 2019    12  25 0.00    1
3 2019    12  26 0.00    1
4 2019    12  27 1.46    1
5 2019    12  28 0.00    1
6 2019    12  29 0.00    1
Duck
  • 39,058
  • 13
  • 42
  • 84
  • If you just are going to separate the string, there is no need to convert to date-format first – Wimpel Sep 07 '20 at 11:37