R重新分配/分配值到一个因子的水平?

时间:2022-08-23 14:54:36

Given a vector v <- seq(0,23). I want to convert it to a factor with the following levels:

给定向量v < - seq(0,23)。我想将它转换为具有以下级别的因子:

0 = All numbers from 0 to 4
1 = All numbers from 5 to 8
2 = Numbers 9, 11, 23
3 = Others

Please guide me how can I do this? I have done factor(v, levels = as.character(seq(0,23))). Then

请指导我怎么做?我做了因子(v,levels = as.character(seq(0,23)))。然后

levels(v[levels(v) %in% as.character(seq(0,4))] <- "0"
levels(v[levels(v) %in% as.character(seq(5,8))] <- "1"
levels(v[levels(v) %in% as.character(c(9,11,23)] <- "2"

2 个解决方案

#1


1  

A couple of options

几个选项

Base R

v <- 0:23
v <- factor(v)

levels(v) <- 
  list("0 - 4" = 0:4,
       "5 - 8" = 5:8,
       "9, 11, 23" = c(9, 11, 23),
       "Others" = levels(v)[!levels(v) %in% c(0:9, 11, 23)])

forcats package (tidyverse paradigm)

library(magrittr)
library(forcats)

v <- 0:23 %>% 
  factor() %>% 
  fct_collapse("0 - 4" = as.character(0:4),
               "5 - 8" = as.character(5:8),
               "9, 11, 23" = as.character(c("9", "11", "23"))) %>% 
  fct_other(keep = c("0 - 4", "5 - 8", "9, 11, 23"),
            other_level = "Others")

#2


1  

A different Base R solution

一种不同的Base R解决方案

v <- 0:23
v <- factor(ifelse(v <= 4, "0", 
            ifelse(v > 4 & v <= 8, "1", 
            ifelse(v %in% c(9,11,23), "2", "3"))))

#1


1  

A couple of options

几个选项

Base R

v <- 0:23
v <- factor(v)

levels(v) <- 
  list("0 - 4" = 0:4,
       "5 - 8" = 5:8,
       "9, 11, 23" = c(9, 11, 23),
       "Others" = levels(v)[!levels(v) %in% c(0:9, 11, 23)])

forcats package (tidyverse paradigm)

library(magrittr)
library(forcats)

v <- 0:23 %>% 
  factor() %>% 
  fct_collapse("0 - 4" = as.character(0:4),
               "5 - 8" = as.character(5:8),
               "9, 11, 23" = as.character(c("9", "11", "23"))) %>% 
  fct_other(keep = c("0 - 4", "5 - 8", "9, 11, 23"),
            other_level = "Others")

#2


1  

A different Base R solution

一种不同的Base R解决方案

v <- 0:23
v <- factor(ifelse(v <= 4, "0", 
            ifelse(v > 4 & v <= 8, "1", 
            ifelse(v %in% c(9,11,23), "2", "3"))))