Changing month name and year to date or POSIXct

后端 未结 2 1091
无人共我
无人共我 2021-01-25 10:24

I have a data frame

             date     df discharge cfs   green discharge cfs   north discharge cfs
1   December 2018        2520.1394           171.69667             


        
相关标签:
2条回答
  • 2021-01-25 10:29

    In base R, we can paste an arbitrary date , convert to date object and then format

    format(as.Date(paste0('1', df$date), '%d %B %Y'), '%m-%Y')
    

    Another option with regex and using an inbuilt vector month.name can be

    with(df, paste(match(sub('\\s\\d+', '', date), month.name), 
                         sub('.*\\s+', '', df$date), sep = '-'))
    
    0 讨论(0)
  • 2021-01-25 10:36

    We can use as.yearmon to convert to yearmon class and then change the format

    library(zoo)
    df1$date <- format(as.yearmon(df1$date, "%B %Y"), "%m-%Y")
    df1$date
    #[1] "12-2018" "11-2018" "10-2018" "04-2019" "08-2019" "02-2019" "01-2019" "07-2019" "06-2019" "03-2019" "05-2019" "11-2019" "10-2019"
    #[14] "09-2019"
    

    data

    df1 <- structure(list(date = c("December 2018", "November 2018", "October 2018", 
    "April 2019", "August 2019", "February 2019", "January 2019", 
    "July 2019", "June 2019", "March 2019", "May 2019", "November 2019", 
    "October 2019", "September 2019"), df_discharge_cfs = c(2520.1394, 
    3475.1023, 1863.4778, 3244.5356, 335.5074, 1631.3048, 1767.6266, 
    496.9439, 1097.2101, 1081.8046, 1507.8582, 2842.3542, 544.3002, 
    295.72), green_discharge_cfs = c(171.69667, 239.00738, 121.9172, 
    260.38507, 14.95659, 94.35956, 132.69408, 26.37159, 64.17292, 
    80.32419, 100.81569, 284.72917, 34.67999, 11.37943), 
    north_discharge_cfs = c(338.81082, 
    422.19063, 200.94455, 543.34792, 29.29938, 198.19885, 247.54493, 
    57.50114, 143.40153, 167.57954, 236.58269, 586.75, 83.58193, 
    26.25823)), class = "data.frame", row.names = c("1", "2", "3", 
    "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"))
    
    0 讨论(0)
提交回复
热议问题