Extract Date in R

后端 未结 3 1559
名媛妹妹
名媛妹妹 2021-01-03 07:50

I struggle mightily with dates in R and could do this pretty easily in SPSS, but I would love to stay within R for my project.

I have a date column in my data fram

3条回答
  •  礼貌的吻别
    2021-01-03 08:24

    Is this what you are looking for?

    library(ggplot2)
    ## make up data for two seasons a and b
    a = as.Date("2010/10/1")
    b = as.Date("2011/10/1")
    a.date <- seq(a, by='1 week', length=28)
    b.date <- seq(b, by='1 week', length=28)
    
    ## make up some score data  
    a.score <- abs(trunc(rnorm(28, mean = 10, sd = 5)))
    b.score <- abs(trunc(rnorm(28, mean = 10, sd = 5)))
    
    ## create a data frame   
    df <- data.frame(a.date, b.date, a.score, b.score)
    df
    
    ## Since I am using ggplot I better create a "long formated" data frame
    df.molt <- melt(df, measure.vars = c("a.score", "b.score"))
    levels(df.molt$variable) <- c("First season", "Second season")
    df.molt
    

    Then, I am using ggplot2 for plotting the data:

    ## plot it
    ggplot(aes(y = value, x = a.date), data = df.molt) + geom_point() +   
    geom_line() + facet_wrap(~variable, ncol = 1) + 
    scale_x_date("Date", format = "%m-%d")
    

    If you want to modify the x-axis (e.g., display format), then you'll probably be interested in scale_date.

    enter image description here

提交回复
热议问题