【问题标题】:Merge two datasets but one of them is year_month and the other is year_month_week合并两个数据集,其中一个是 year_month,另一个是 year_month_week
【发布时间】:2022-07-26 22:38:19
【问题描述】:

我现在使用 R 练习数据合并。这里是简单的两个数据df1df2

df1<-data.frame(id=c(1,1,1,2,2,2,2),
                year_month=c(202205,202206,202207,202204,202205,202206,202207),
                points=c(65,58,47,21,25,27,43))

df2<-data.frame(id=c(1,1,1,2,2,2),
                year_month_week=c(2022052,2022053,2022061,2022043,2022051,2022052),
                temperature=c(36.1,36.3,36.6,34.3,34.9,35.3))

对于df1202205year_month 列中表示 2022 年 5 月。 对于df22022052 列中的2022052 表示 2022 年 5 月的第 2 周。 我想相对于year_month_week 合并df1df2。所以,df2 的所有元素都被保留了,但可以复制df2 的一些值。 例如,year_month 中的202205 包括20220522022053df2 中没有列 points。在这种情况下,65 被复制。我的预期输出如下所示:

df<-data.frame(id=c(1,1,1,2,2,2),
               year_month_week=c(2022052,2022053,2022061,2022043,2022051,2022052),
               temperature=c(36.1,36.3,36.6,34.3,34.9,35.3),
               points=c(65,65,58,21,25,25))

【问题讨论】:

    标签: r dataframe datetime merge datetime-format


    【解决方案1】:

    通过取year_month_week 的前六个字符在df2 中创建一个临时的year_month 列,然后通过year_monthiddf1 上执行merge

    您可以轻松地将临时 year_month 列子集化。

    df2$year_month <- substr(df2$year_month_week, 1, 6)
    merge(df2, df1, by = c('year_month', 'id'))[-1]
    #>   id year_month_week temperature points
    #> 1  2         2022043        34.3     21
    #> 2  1         2022052        36.1     65
    #> 3  1         2022053        36.3     65
    #> 4  2         2022051        34.9     25
    #> 5  2         2022052        35.3     25
    #> 6  1         2022061        36.6     58
    

    【讨论】:

      猜你喜欢
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2017-07-12
      • 2015-04-09
      • 2017-12-01
      • 2022-06-11
      相关资源
      最近更新 更多