-2

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

    answer
      1
      2
      1
      2

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

     answer
       NO
       YES
       NO
       YES

我应该对survey$answer 数据应用什么命令?

其实我想做的是用格子可视化数据

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

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

在此处输入图像描述

4

4 回答 4

4

使用factor函数如下:

> answer <- c(1,2,1,2)
> answer <- factor(answer, labels=c("NO", "YES"))
[1] NO  YES NO  YES
Levels: NO YES
于 2013-08-26T14:03:05.777 回答
1

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

answer <- rep(1:2,2)
answer <- as.factor(answer)
levels(answer) <- c("NO","YES")
于 2013-08-26T14:03:31.327 回答
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])

在此处输入图像描述

于 2013-08-26T16:50:44.113 回答
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
于 2013-08-26T14:01:00.667 回答