0

我有两个每周数据集,一个在星期三收集,一个在星期五收集:

 library(lubridate)


 #Data set released Wed
 Date1 <- c("02/10/2013","9/10/2013","16/10/2013","23/10/2013")
 Data1 <- c(1,2,3,4)

 df1 <- data.frame(Date1 ,Data1)
 df1

 #Weekly Data Set released Fri

 Date2 <- c("04/10/2013","11/10/2013","18/10/2013","25/10/2013")
 Data2 <- c(2,4,6,8)

 df2 <- data.frame(Date2 ,Data2)
 df2

然后我想按一年中的一周合并

 week(df1$Date1)

[1] 42 42 43 42

 week( df2$Date2 )

[1] 43 42 42 42

但我似乎得到了不正确的输出。

如果您能帮助我了解我做错了什么,我将不胜感激。

4

2 回答 2

1
> df1$week <- format(df1$Date1, "%U")
> df2$week<- format(df2$Date2, "%U")
> df1
       Date1 Data1 week
1 2013-10-02     1 39
2 2013-10-09     2 40
3 2013-10-16     3 41
4 2013-10-23     4 42
> df2
       Date2 Data2 week
1 2013-10-04     2 39
2 2013-10-11     4 40
3 2013-10-18     6 41
4 2013-10-25     8 42

> merge(df1, df2, by="week")
  week    Date1 Data1      Date2 Data2
1 39 2013-10-02     1 2013-10-04     2
2 40 2013-10-09     2 2013-10-11     4
3 41 2013-10-16     3 2013-10-18     6
4 42 2013-10-23     4 2013-10-25     8
于 2013-10-12T09:12:33.230 回答
0

你的意思是按日期合并和排序?

    library(chron)

    names(df1) = names(df2) = c("Date", "Data") #change names for a successfull rbind

    DF <- rbind(df1, df2)
    DF

            #Date Data
    #1 02/10/2013    1
    #2  9/10/2013    2
    #3 16/10/2013    3
    #4 23/10/2013    4
    #5 04/10/2013    2
    #6 11/10/2013    4
    #7 18/10/2013    6
    #8 25/10/2013    8

    dates <- chron(as.character(DF$Date), format = c(dates = "d/m/y", times = "h:m:s"))

    DF[order(dates),] #sort by date 
            #Date Data
    #1 02/10/2013    1
    #5 04/10/2013    2
    #2  9/10/2013    2
    #6 11/10/2013    4
    #3 16/10/2013    3
    #7 18/10/2013    6
    #4 23/10/2013    4
    #8 25/10/2013    8 
于 2013-10-11T22:30:12.680 回答