【问题标题】:How to organise a date in 3 different columns in r?如何在 r 的 3 个不同列中组织日期?
【发布时间】:2021-04-07 16:12:28
【问题描述】:

我有很多像这样按日期组织的气候数据。

df = data.frame(date = c("2011-03-24", "2011-02-03", "2011-01-02"), Precipitation = c(20, 22, 23))

我想像这样组织它

df = data.frame(year = c("2011", "2011","2011"), month = c("03","02","01"), day = c("24", "03", "02"), pp = c(20, 22, 23))

我有很多信息,我无法手动完成。

有人可以帮我吗?非常感谢。

【问题讨论】:

    标签: r dataframe date


    【解决方案1】:

    使用 strsplit 你可以这样做:

    逻辑:strsplit 将用破折号分割日期以创建 3 个元素的列表,每个元素包含年、月和日的 3 个部分。我们使用 rbind 绑定这些元素,但要迭代地进行。我们使用 do.call,所以 do.call 会将这些列表元素行绑定成 3 行。由于结果是一个矩阵,我们将其转换为数据框,然后使用 setNames 为列赋予新名称。最后的 cbind 会将这些 3x3 数据帧与原始沉淀绑定。

    cbind(setNames(data.frame(do.call('rbind', strsplit(df$date, '-'))), c('Year', 'month', 'day')), 'Precipitation' = df$Precipitation)
    

    输出

     Year month day Precipitation
    1 2011    03  24            20
    2 2011    02  03            22
    3 2011    01  02            23
    

    【讨论】:

    • 非常感谢:3
    【解决方案2】:

    这将返回年、月和日的整数值。如果你真的需要它们作为用0 填充的字符,你可以在结果上使用formatC(x, width = 2, flag = "0")

    library(clock)
    library(dplyr)
    
    df <- data.frame(
      date = c("2011-03-24", "2011-02-03", "2011-01-02"), 
      pp = c(20, 22, 23)
    )
    
    df %>%
      mutate(
        date = as.Date(date),
        year = get_year(date),
        month = get_month(date),
        day = get_day(date)
      )
    #>         date pp year month day
    #> 1 2011-03-24 20 2011     3  24
    #> 2 2011-02-03 22 2011     2   3
    #> 3 2011-01-02 23 2011     1   2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多