我有一个因素
one = A,B
two = C,D
three = E,F
我想制作一个新的因素,其中一级,二级,三级
new_factor
[1] one one two two three three
Levels: one two three
所以新因素看起来像
Keyboard.Focus(autocompletetextbox);
autocompletetextbox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
我该如何处理?
答案 0 :(得分:2)
?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
或者,如果您不想覆盖该对象:
`levels<-`(x, list("one" = c("A","B"), "two" = c("C","D"), "three" = c("E","F")))
答案 1 :(得分:1)
我们可以使用gl
创建一个分组变量split
vector
,并将其作为键/值list
,stack
使用它创建data.frame
并提取&#39; ind&#39;柱
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
或者我们可以使用rep
factor(rep(c('one', 'two', 'three'), each = 2), levels = c('one', 'two', 'three'))
如果OP想要替换特定元素&#34; A&#34;,&#34; B&#34;用&#34;一个&#34;,&#34; C&#34;,&#34; D&#34;用&#34;两个&#34;而不是基于位置,
set.seed(24)
factor2 <- sample(LETTERS[1:6], 20, replace=TRUE)
unname(setNames(rep(c("one", "two", "three"), each = 2), LETTERS[1:6])[factor2])
注意:在这里,我假设最初的vector
是character
类。
答案 2 :(得分: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
答案 3 :(得分:0)
一种方法是使用switch
(sapply
循环播放)。
new.factor <- sapply(factor, function(x) switch(x,
A = "one",
B = "one",
C = "two",
D = "two",
E = "three",
F = "three"))
然后,您可以使用as.factor
将其更改为因子类对象。
new.factor <- as.factor(new.factor)