【问题标题】:Year column and Month column into Date colum R年列和月列转换为日期列 R
【发布时间】:2020-11-21 17:47:14
【问题描述】:

我有 2 个日期列(年和月)的数据框,我想将它们合并为 1 个(我将在绘制 x 轴时使用该列)。

如何合并它们,使其中的值看起来像 "1990-03"

structure(list(Year = c(1983, 1983, 1983, 1983, 1983, 1983), 
    Month = c(5, 6, 7, 8, 9, 10), MEI = c(2.556, 2.167, 1.741, 
    1.13, 0.428, 0.002), CO2 = c(345.96, 345.52, 344.15, 342.25, 
    340.17, 340.3), CH4 = c(1638.59, 1633.71, 1633.22, 1631.35, 
    1648.4, 1663.79), N2O = c(303.677, 303.746, 303.795, 303.839, 
    303.901, 303.97), CFC.11 = c(191.324, 192.057, 192.818, 193.602, 
    194.392, 195.171), CFC.12 = c(350.113, 351.848, 353.725, 
    355.633, 357.465, 359.174), TSI = c(1366.1024, 1366.1208, 
    1366.285, 1366.4202, 1366.2335, 1366.0589), Aerosols = c(0.0863, 
    0.0794, 0.0731, 0.0673, 0.0619, 0.0569), Temp = c(0.109, 
    0.118, 0.137, 0.176, 0.149, 0.093)), row.names = c(NA, 6L
), class = "data.frame")

我尝试了一些方法,但不断收到NA

【问题讨论】:

  • 尝试:df %>% mutate(YM = str_c(Year, Month, sep = '-'))

标签: r


【解决方案1】:

您可以使用sprintf 将月份格式化为两位数并粘贴年份:

sprintf("%04d-%02d",df$Year,df$Month)
[1] "1983-05" "1983-06" "1983-07" "1983-08" "1983-09" "1983-10"
df$Date <- sprintf("%04d-%02d",df$Year,df$Month)
## dplyr alternative
df %>% mutate(Date=sprintf("%04d-%02d",df$Year,df$Month))
  Year Month   MEI    CO2     CH4     N2O  CFC.11  CFC.12      TSI Aerosols  Temp    Date
1 1983     5 2.556 345.96 1638.59 303.677 191.324 350.113 1366.102   0.0863 0.109 1983-05
2 1983     6 2.167 345.52 1633.71 303.746 192.057 351.848 1366.121   0.0794 0.118 1983-06
3 1983     7 1.741 344.15 1633.22 303.795 192.818 353.725 1366.285   0.0731 0.137 1983-07
4 1983     8 1.130 342.25 1631.35 303.839 193.602 355.633 1366.420   0.0673 0.176 1983-08
5 1983     9 0.428 340.17 1648.40 303.901 194.392 357.465 1366.234   0.0619 0.149 1983-09
6 1983    10 0.002 340.30 1663.79 303.970 195.171 359.174 1366.059   0.0569 0.093 1983-10

为了完整性(改进@KarthikS的评论)你可以使用stringr::str_c和stringr::str_pad后者用0s和前者连接年和月

str_c(df$Year, str_pad(df$Month, 2, pad=0), sep='-')
[1] "1983-05" "1983-06" "1983-07" "1983-08" "1983-09" "1983-10"

【讨论】:

猜你喜欢
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2019-03-01
相关资源
最近更新 更多