如何将虚拟变量转换为R中的因子?

时间:2013-08-26 13:58:46

标签: r

在我的数据框(称为调查)中,有一个名为“answer”的变量

    answer
      1
      2
      1
      2

我想将这些虚拟变量转换为

     answer
       NO
       YES
       NO
       YES

我应该用什么命令来调查$答案数据?

实际上我想做的是用格子来显示数据

   barchart(as.factor(with(survey, survey$answer)))

以上命令确实产生了条形图,但我需要将标签更改为“是”和“否”而不是“2”和“1”。这就是我需要转换虚拟变量的原因。

enter image description here

4 个答案:

答案 0 :(得分:4)

使用factor功能,如:

> answer <- c(1,2,1,2)
> answer <- factor(answer, labels=c("NO", "YES"))
[1] NO  YES NO  YES
Levels: NO YES

答案 1 :(得分:1)

指标的答案会给你一个字符变量。对于一个因素:

answer <- rep(1:2,2)
answer <- as.factor(answer)
levels(answer) <- c("NO","YES")

答案 2 :(得分:1)

为了好玩,这是另一种选择。它并不打算转换为一个因素,但这也不是你的条形图所必需的:

set.seed(1)
x <- sample(2, 50, replace = TRUE)
x
#  [1] 1 1 2 2 1 2 2 2 2 1 1 1 2 1 2 1 2 2 1 2 2 1 2 1 1 1 1 1 2 1 1 2
# [33] 1 1 2 2 2 1 2 1 2 2 2 2 2 2 1 1 2 2
c("NO", "YES")[x]
#  [1] "NO"  "NO"  "YES" "YES" "NO"  "YES" "YES" "YES" "YES" "NO" 
# [11] "NO"  "NO"  "YES" "NO"  "YES" "NO"  "YES" "YES" "NO"  "YES"
# [21] "YES" "NO"  "YES" "NO"  "NO"  "NO"  "NO"  "NO"  "YES" "NO" 
# [31] "NO"  "YES" "NO"  "NO"  "YES" "YES" "YES" "NO"  "YES" "NO" 
# [41] "YES" "YES" "YES" "YES" "YES" "YES" "NO"  "NO"  "YES" "YES"

这是你的条形图:

library(lattice)
barchart(c("NO", "YES")[x])

enter image description here

答案 3 :(得分:0)

   answer<-ifelse(answer==1,"NO","YES")
> answer
[1] "NO"  "YES" "NO"  "YES"

> as.factor(answer)
[1] No  YES No  YES
Levels: No YES

或者,使用汽车套件中的recode

answer<-recode(answer,"1='No';else='YES'")
> answer
[1] "No"  "YES" "No"  "YES"


  > as.factor(answer)
[1] No  YES No  YES
Levels: No YES