【问题标题】:Apply which.min on POSIXct在 POSIXct 上应用 which.min
【发布时间】:2016-08-04 08:39:59
【问题描述】:

我试图从POSIXct 的数据框中找到逐行最小值。但是使用applywhich.min 不起作用:

df <- data.frame(date1 = as.POSIXct(c("2016-01-01", "2016-02-01")),
                 date2 = as.POSIXct(c("2015-10-01", "2016-06-01")))

apply(df, 1, which.min) # not OK
# integer(0)
# Warning messages:
# 1: In FUN(newX[, i], ...) : NAs introduced by coercion
# 2: In FUN(newX[, i], ...) : NAs introduced by coercion

apply(df, 1, function(x) which(x == min(x))) # OK
# [1] 2 1

sapply(1:nrow(df), function(i) which.min(df[i,])) # OK
# date2 date1 
# 2     1 

谁能解释这种行为?

【问题讨论】:

  • 我认为applydf[1,] 转换为as.matrix,这将导致值是which.min 无法解释的字符类型。

标签: r apply posixct


【解决方案1】:

看看这个:

str(apply(df, 1, identity))
# chr [1:2, 1:2] "2016-01-01" "2015-10-01" "2016-02-01" "2016-06-01"
# - attr(*, "dimnames")=List of 2
#  ..$ : chr [1:2] "date1" "date2"
#  ..$ : NULL

应用identity 会将 POSIXct 值转换为字符!发生这种情况是因为apply 将其输入强制转换为矩阵,as.matrix.data.frame 在 POSIXct 值上使用format,因为矩阵只能保存原子值,而像 POSIXct 这样的 S3 对象不是原子的。因此得到的矩阵是一个字符矩阵。而且您无法计算最少的字符。 sapply 对其输入进行迭代,并且不会将 data.frame 转换为矩阵。

【讨论】:

  • 好的,谢谢。这有点奇怪,因为 min 函数可以应用于字符向量。这意味着 which(x == min(x)) 解决方案会比较字符而不是 POSIXcts,并且可能会产生意想不到的结果!
猜你喜欢
  • 2015-03-07
  • 2015-07-07
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多