Arczi
Arczi

Reputation: 143

R factors get numbers from to

I have list of numbers for example 0,1,0,1,2,3,0,5,6,7,5

w=factor(data,levels=c(a=0,b=1,2>))

In 2> I want to have levels above then 2 but I don't want to have more levels then 3(0,1,above 2).

Upvotes: 0

Views: 50

Answers (2)

giocomai
giocomai

Reputation: 3518

This should achieve what you asked:

library("tidyverse")

c(0,1,0,1,2,3,0,5,6,7,5) %>% 
  as.character() %>% 
  as_factor() %>% 
  fct_other(keep = c("1", "2"))
#>  [1] Other 1     Other 1     2     Other Other Other Other Other Other
#> Levels: 1 2 Other

Upvotes: 1

Bulat
Bulat

Reputation: 6979

You can limit values with pmin:

v <- c(0,1,0,1,2,3,0,5,6,7,5)
pmin(v, 2)
# [1] 0 1 0 1 2 2 0 2 2 2 2

Upvotes: 1

Related Questions