开发者

In R, how do I map numeric values to factors, including Inf and NaN?

Using R, I have a vector such as

a <- c(0.1,0.6,23,Inf,NaN)

I would like to convert it to something like

c("Finite",开发者_如何学运维"Finite","Finite","Inf","NaN")

with as little pain as possible. How is this done?

Thanks! Uri


ifelse() seems to work reasonably well:

b <- ifelse(is.finite(a), "Finite", ifelse(is.infinite(a), "Infinite", "NaN"))
> b
[1] "Finite"   "Finite"   "Finite"   "Infinite" "NaN" 

Technically, that returns a character vector, which can be converted with as.factor() or just wrap factor() around the initial call to return a factor to begin with...though character may suit your needs depending on what you need to do.


You could also use match (and don't forget about NA's):

f <- function(x) {
    codes <- c("NaN", "Inf", "Inf", "NA", "Finite")
    codes[match(x, c(NaN, Inf, -Inf, NA), nomatch=5L)]
}

f(a)
# [1] "Finite" "Finite" "Finite" "Inf"    "NaN"

f(c(7.777, -Inf, NA, Inf, NaN, 0/0))
# [1] "Finite" "Inf"    "NA"     "Inf"    "NaN"    "NaN"


Here's a variant that uses R's own names except for "Finite" - so it's a bit shorter to write and as a bonus also handles negative infinity and NA:

# Include -Inf and NA...
a <- c(0.1,0.6,23,Inf,-Inf,NaN,NA)

format(ifelse(is.finite(a), "Finite", a), justify="none")
#[1] "Finite" "Finite" "Finite" "Inf"    "-Inf"   "NaN"    "NA"  

...But if you really want the strings "Infinity" and "-Infinity", then this would do that:

sub("Inf", "Infinity", format(ifelse(is.finite(a), "Finite", a), justify="none"))

Finally, if you want to keep the NAs, then just don't call format:

sub("Inf", "Infinity", ifelse(is.finite(a), "Finite", a))
#[1] "Finite"    "Finite"    "Finite"    "Infinity"  "-Infinity" "NaN"       NA   


Another method can be something like this (similarly to question Recoding Numeric Vector):

type <- rep("Finite", length(a))
type[is.nan(a)] <- "NaN"
type[is.infinite(a)] <- "Infinite"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜