【问题标题】:Restructure the date in multiple columns at the same time in R在R中同时重组多列中的日期
【发布时间】:2020-06-25 17:11:36
【问题描述】:

我有多个数据框,每个数据框代表 2016 - 2019 年的数据(即 df.16、df.17、df.18、df.19),我想转换 date YYYY/MM/DD 00:00:00 中的每个列以简单地显示月份。我想通过创建一个新列month 并对所有数据帧同时执行此操作来完成此操作。我认为我应该使用lapply,尽管我不完全确定。我的代码如下:

制作清单: df.list <- list(df.16, df.17, df.18, df.19, df.20)

应用功能: lapply(df.list, function(x) {x$month <- month(date); x})

但是,我不断收到以下错误:Error in as.POSIXlt.default(x, tz = tz(x)) : do not know how to convert 'x' to class “POSIXlt”

任何帮助将不胜感激!

【问题讨论】:

    标签: r list date lapply posixlt


    【解决方案1】:

    我使用以下方法解决了这个问题:

    new_df_list <- lapply(df.list, function(df) within(df, month <- month(date)))

    【讨论】:

      【解决方案2】:

      另一个选项是transform,我们不必使用匿名函数

      new_df_list <- lapply(df.list, transform, month = month(date))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 2017-02-02
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        • 2015-08-19
        相关资源
        最近更新 更多