2

I have a factor

factor <- c("A", "B", "C", "D", "E", "F")

I want to make a new factor with levels one,two,three where

one = A,B  
two = C,D
three = E,F

So the new factor will look like

new_factor 
[1] one one two two three three
Levels: one two three

How should I approach this?

hello
  • 137
  • 1
  • 2
  • 5

4 Answers4

2

This is described in the help file for ?levels:

x <- factor(LETTERS[1:6])
x
#[1] A B C D E F
#Levels: A B C D E F
levels(x) <- list("one" = c("A","B"), "two" = c("C","D"), "three" = c("E","F"))
x
#[1] one   one   two   two   three three
#Levels: one two three

Or if you don't want to overwrite the object:

`levels<-`(x, list("one" = c("A","B"), "two" = c("C","D"), "three" = c("E","F")))
thelatemail
  • 91,185
  • 12
  • 128
  • 188
1

We can use gl to create a grouping variable, split the vector with that and make it as a key/value list, stack it to create a data.frame and extract the 'ind' column

d1 <- stack(setNames(split(factor, as.numeric(gl(length(factor), 
             2, length(factor)))), c("one", "two", "three")))
new_factor <- factor(d1$ind, levels = c("one", "two", "three"))
new_factor
#[1] one   one   two   two   three three
#Levels: one two three

Or we can use rep

factor(rep(c('one', 'two', 'three'), each = 2), levels = c('one', 'two', 'three'))

Update

If the OP want to replace the specific elements "A", "B" with "one", "C", "D" with "two" instead of based on the position,

 set.seed(24)
 factor2 <- sample(LETTERS[1:6], 20, replace=TRUE)
 unname(setNames(rep(c("one", "two", "three"), each = 2), LETTERS[1:6])[factor2])

NOTE: Here, I assumed that the initial vector is character class.

akrun
  • 874,273
  • 37
  • 540
  • 662
1
factor <- c("A", "B", "C", "D", "E", "F")
names(factor) <- c(rep("one",2),rep("two",2),rep("three",2))
new_factor <- as.factor((names(factor)))
print(new_factor)
[1] one   one   two   two   three three
Levels: one three two
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22
0

One way would be to use switch (with sapply to loop through the vector).

 new.factor <- sapply(factor,  function(x) switch(x,
                      A = "one",
                      B = "one",
                      C = "two",
                      D = "two",
                      E = "three",
                      F = "three"))

You can then change it into a factor class object with as.factor.

new.factor <- as.factor(new.factor)
Noah
  • 3,437
  • 1
  • 11
  • 27