这两个命令在R中有什么区别?(因子变量的级别)

时间:2018-11-26 20:07:15

标签: r

我是R的新手,我试图弄清楚最后两个命令之间的区别是什么?因为输出完全相同。

yesno <- sample(c("yes", "no"),size = 10, replace = TRUE);yesno
> yesno
[1] "yes" "yes" "no"  "yes" "yes" "yes" "no"  "yes" "no"  "yes"

yesnofac <- factor(yesno, levels = c("yes", "no"));yesnofac
[1] yes yes no  yes yes yes no  yes no  yes
Levels: yes no

relevel(yesnofac, ref = "yes")   #Reorder Levels of Factor
[1] yes yes no  yes yes yes no  yes no  yes
Levels: yes no

1 个答案:

答案 0 :(得分:1)

在上面的示例中,没有区别,因为第一级为“是”。但是,如果我们更改levels的顺序,则relevel会将“是”作为第一个level

yesnofac <- factor(yesno, levels = c("no", "yes"))
yesnofac
#[1] yes no  yes yes yes yes yes no  yes yes
# Levels: no yes

relyesnofac <- relevel(yesnofac, ref = "yes")
relyesnofac
#[1] yes no  yes yes yes yes yes no  yes yes
# Levels: yes no'

检查levels,现在在order中有所不同

levels(relyesnofac)
#[1] "yes" "no" 
levels(yesnofac)
#[1] "no"  "yes"