【问题标题】:How to get a result of the correct class when concatenating data in R?在 R 中连接数据时如何获得正确类的结果?
【发布时间】:2013-07-25 05:22:12
【问题描述】:

我发现crbind 的结果类基于第一个参数的类。这给我带来了一个问题,因为NA 作为第一个参数的存在将Date 向量强制转换为numeric 向量。比较这两个class 调用的结果:

x <- Sys.Date()
y <- NA
class(c(x, y)) # "Date"
class(c(y, x)) # "numeric"

同样适用于rbind

x <- data.frame(column=Sys.Date())
y <- data.frame(column=NA)
class(rbind(x, y)$column) # "Date"
class(rbind(y, x)$column) # "numeric"

无论参数的顺序如何,如何确保这些连接的结果始终是 Date 向量?

【问题讨论】:

    标签: r class concatenation rbind


    【解决方案1】:

    将第一个参数强制转换为所需的类:

    c(as.Date(y), x)
    c(as.Date(x), y)
    

    【讨论】:

      【解决方案2】:

      明确使用你想要的方法:

      c.Date(y,x)
      

      【讨论】:

      • 这对c 很有帮助,但我也可以为rbind 做类似的事情吗?
      • 是的,将y$column的类设置为Datey &lt;- data.frame(column=as.Date(NA))
      猜你喜欢
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      相关资源
      最近更新 更多