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.