【问题标题】:apply making conversion (POSIXct)申请转换 (POSIXct)
【发布时间】:2018-06-25 13:31:15
【问题描述】:

我在带有 POSIXct 对象的 data.frame 上使用 apply。 问题是 apply 从将输入 data.frame 转换为.matrix() 开始(根据what I read)。这意味着 POSIXct 将被转换为 char。

我改用 lapply 解决了我的问题。但是有更好的解决方案吗?

    # data.frame with one column of posixct
    pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
    str(pos) # POSIXct

    test = function(x){
      str(x[1])
      return(x)
    }                 
    res = data.frame(apply(pos, 2, test))
    str(res) # all strings

    res2 = data.frame(lapply(pos, test))
    str(res2) # all POSIXct

【问题讨论】:

    标签: r type-conversion apply


    【解决方案1】:

    您可以使用 purrr 包中的 map_df 函数。 map 函数针对不同的输出类型有不同的版本,因此对于这种情况,您可以使用 map_df

    # data.frame with one column of posixct
    pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
    str(pos) # POSIXct
    
    test = function(x){
      str(x[1])
      return(x)
    }                 
    res = data.frame(apply(pos, 2, test))
    str(res) # all strings
    
    res2 = data.frame(lapply(pos, test))
    str(res2) # all POSIXct
    
    library(purrr)
    
    res3 = map_df(pos, test)
    str(res3)
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多