`as.na`功能

flo*_*del 19 r

在R中,is.*我能想到的几乎所有功能都有相应的功能as.*.有一个is.na但没有as.na.为什么不,如果这样的功能有意义,你将如何实现?

我有一个载体x,可以是logical,character,integer,numericcomplex,我想将其转换为同一类别和长度的矢量,但充满了适当的:NA,NA_character_,NA_integer_,NA_real_,或NA_complex_.

我目前的版本:

as.na <- function(x) {x[] <- NA; x}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ich 15

为什么不is.na<-按照指示使用?is.na

> l <- list(integer(10), numeric(10), character(10), logical(10), complex(10))
> str(lapply(l, function(x) {is.na(x) <- seq_along(x); x}))
List of 5
 $ : int [1:10] NA NA NA NA NA NA NA NA NA NA
 $ : num [1:10] NA NA NA NA NA NA NA NA NA NA
 $ : chr [1:10] NA NA NA NA ...
 $ : logi [1:10] NA NA NA NA NA NA ...
 $ : cplx [1:10] NA NA NA ...
Run Code Online (Sandbox Code Playgroud)

  • 当然,但`is.na <-`是通用的,可以为它编写方法; 我不确定你或OP的解决方案如何处理其他类.我在考虑速度前的稳健性. (4认同)

Jos*_*ien 12

这似乎一直比你的功能更快:

as.na <- function(x) {
    rep(c(x[0], NA), length(x))
}
Run Code Online (Sandbox Code Playgroud)

(感谢Joshua Ulrich指出我的早期版本没有保留类属性.)


在这里,为了记录,是一些相对时间:

library(rbenchmark)

## The functions
flodel <- function(x) {x[] <- NA; x}
joshU <- function(x) {is.na(x) <- seq_along(x); x}
joshO <- function(x) rep(c(x[0], NA), length(x))

## Some vectors to  test them on
int  <- 1:1e6
char <- rep(letters[1:10], 1e5)
bool <- rep(c(TRUE, FALSE), 5e5)

benchmark(replications=100, order="relative",
    flodel_bool = flodel(bool),
    flodel_int  = flodel(int),
    flodel_char = flodel(char),
    joshU_bool = joshU(bool),
    joshU_int  = joshU(int),
    joshU_char = joshU(char),
    joshO_bool = joshO(bool),
    joshO_int  = joshO(int),
    joshO_char = joshO(char))[1:6]        
#          test replications elapsed relative user.self sys.self
# 7  joshO_bool          100    0.46    1.000      0.33     0.14
# 8   joshO_int          100    0.49    1.065      0.31     0.18
# 9  joshO_char          100    1.13    2.457      0.97     0.16
# 1 flodel_bool          100    2.31    5.022      2.01     0.30
# 2  flodel_int          100    2.31    5.022      2.00     0.31
# 3 flodel_char          100    2.64    5.739      2.36     0.28
# 4  joshU_bool          100    3.78    8.217      3.13     0.66
# 5   joshU_int          100    3.95    8.587      3.30     0.64
# 6  joshU_char          100    4.22    9.174      3.70     0.51
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 11

该函数不存在,因为它不是类型转换.类型转换将1L更改为1.0,或将"1"更改为1L.NA类型不是来自其他类型的转换,除非该类型是文本.鉴于只有一种类型可以转换,并且有很多选项可以进行NA的分配(就像许多其他答案一样),不需要这样的功能.

你得到的每一个答案都只是将NA分配给传入它的所有内容,但你可能只想有条件地做到这一点.有条件地进行赋值或调用一个小包装器也没有什么不同.