20

In R, almost every is.* function I can think of has a corresponding as.*. There is a is.na but no as.na. Why not and how would you implement one if such function makes sense?

I have a vector x that can be logical, character, integer, numeric or complex and I want to convert it to a vector of same class and length, but filled with the appropriate: NA, NA_character_, NA_integer_, NA_real_, or NA_complex_.

My current version:

as.na <- function(x) {x[] <- NA; x}
4

4 に答える 4

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 ...
于 2012-12-18T16:57:34.320 に答える
13

これは、関数よりも一貫して高速であるようです:

as.na <- function(x) {
    rep(c(x[0], NA), length(x))
}

(以前のバージョンではクラス属性が保持されていなかったことを指摘してくれた 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
于 2012-12-18T16:55:56.293 に答える
11

型変換ではないため、関数は存在しません。型変換は、1L を 1.0 に変更するか、「1」を 1L に変更します。NA 型は、その型がテキストでない限り、別の型からの変換ではありません。変換できる型が 1 つしかなく、(他の多くの回答のように) NA の割り当てを行うためのオプションが非常に多いことを考えると、そのような関数は必要ありません。

得られたすべての回答は、渡されたすべてのものに NA を割り当てるだけですが、おそらく条件付きでのみ実行したいでしょう。条件付きで割り当てを行う場合も、小さなラッパーを呼び出す場合も同じです。

于 2012-12-18T17:38:45.040 に答える