【问题标题】:Convert columns to posixct using sapply and keeping datetime format in R使用 sapply 将列转换为 posixct 并在 R 中保持日期时间格式
【发布时间】:2019-11-04 15:41:32
【问题描述】:

我想使用sapply(或类似的东西)将某些列转换为 R data.frame 中的 POSIXct,但保持列的日期时间格式。当我目前这样做时,它会将格式转换为数字。我怎样才能做到这一点?下面是一个例子。

#sample dataframe
df <- data.frame(
  var1=c(5, 2),
  char1=c('he', 'she'),
  timestamp1=c('2019-01-01 20:30:08', '2019-01-02 08:27:34'),
  timestamp2=c('2019-01-01 12:24:54', '2019-01-02 10:57:47'),
  stringsAsFactors = F
)

#Convert only columns with 'timestamp' in name to POSIXct
df[grep('timestamp', names(df))] <- sapply(df[grep('timestamp', names(df))], function(x) as.POSIXct(x, format='%Y-%m-%d %H:%M:%S'))
df
  var1 char1 timestamp1 timestamp2
1    5    he 1546392608 1546363494
2    2   she 1546435654 1546444667

注意:我可以使用as.posixlt 而不是as.posixct,它可以工作,但我想要POSIXct 格式的数据。我还尝试先转换为 POSIXlt,然后再转换为 POSIXct,但这也最终将列转换为数字。

【问题讨论】:

    标签: r posixct


    【解决方案1】:

    使用lapply 而不是sapplysapply 中的“s”用于简化,它将结果转换为矩阵,但 sapply 无法创建 POSIXct 值的矩阵,因此它被转换为简单的数字矩阵。但是,如果您将其保留为列表,则不会失去课程。

    df[grep('timestamp', names(df))] <- lapply(df[grep('timestamp', names(df))], function(x) as.POSIXct(x, format='%Y-%m-%d %H:%M:%S'))
    

    您也可以使用 dplyr 轻松做到这一点

    library(dplyr)
    df %>% mutate_at(vars(contains("timestamp")), as.POSIXct)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2020-09-20
      • 2020-06-18
      • 2012-11-26
      • 2021-03-19
      相关资源
      最近更新 更多