4

在构建数据框时,如果长度不同,则会复制列。

> data.frame(x = c(1,2), y = NA_integer_)
  x  y
1 1 NA
2 2 NA

但是,当我尝试使用 执行此操作时bit64::NA_integer64_,出现错误。有谁知道会发生什么?rep()如果在 上单独调用它就可以工作bit64::NA_integer64_

> data.frame(x = c(1,2), y = bit64::NA_integer64_)
Error in data.frame(x = c(1, 2), y = bit64::NA_integer64_) : 
  arguments imply differing number of rows: 2, 1
> rep(bit64::NA_integer64_, 2)
integer64
[1] <NA> <NA>
4

1 回答 1

1

data.frame只会回收:

  • 没有其他属性的向量names
  • factor
  • AsIs character
  • Date
  • POSIXct

tibble没有这个问题。

tibble::tibble(x = c(1,2), y = bit64::NA_integer64_)
#> # A tibble: 2 x 2
#>       x       y
#>   <dbl> <int64>
#> 1     1      NA
#> 2     2      NA

这是来自的相关片段data.frame

for (i in seq_len(n)[nrows < nr]) {
    xi <- vlist[[i]]
    if (nrows[i] > 0L && (nr%%nrows[i] == 0L)) {
        xi <- unclass(xi)
        fixed <- TRUE
        for (j in seq_along(xi)) {
            xi1 <- xi[[j]]
            if (is.vector(xi1) || is.factor(xi1)) 
              xi[[j]] <- rep(xi1, length.out = nr)
            else if (is.character(xi1) && inherits(xi1, "AsIs")) 
              xi[[j]] <- structure(rep(xi1, length.out = nr), 
                class = class(xi1))
            else if (inherits(xi1, "Date") || inherits(xi1, "POSIXct")) 
              xi[[j]] <- rep(xi1, length.out = nr)
            else {
              fixed <- FALSE
              break
            }
        }
        if (fixed) {
            vlist[[i]] <- xi
            next
        }
    }
    stop(gettextf("arguments imply differing number of rows: %s", 
        paste(unique(nrows), collapse = ", ")), domain = NA)
}
于 2020-10-28T13:46:18.500 回答