简体   繁体   中英

Simplifying a numeric vector to a factor with two levels in R

Suppose I have a 'double' vector

c(-5,-5,-5,-5,1,2,-5,4,3)

I want to set all values having -5 as one factor, and all others as another factor, so that I would have something like:

[1] w w w w b b w b b
Levels: b w

I have a way of doing this but it is not elegant, are there any recommended approaches for this type of conversion?

We can do this with

factor(c("w", "b")[(v1 >0)+1])
#[1] w w w w b b w b b
#Levels: b w

Or using ifelse

factor(ifelse(v1 > 0, "b", "w"))
#[1] w w w w b b w b b
#Levels: b w

data

v1 <- c(-5,-5,-5,-5,1,2,-5,4,3)

The package forcats contains a lot of nice functions for working with factors. One way to solve your problem is like this:

library(forcats)
v1 <- as.factor(c(-5,-5,-5,-5,1,2,-5,4,3))
fct_recode(fct_other(v1, keep = "-5", other_level = "b"), w = "-5")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM