如何将数字变量更改为分类变量

时间:2019-04-17 10:01:26

标签: r vector replace

im试图将“ Wine”变量更改为分类变量

wine_df
wine_df$Wine
  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [38] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 [75] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
[112] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
[149] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

创建A = 1,B = 2,C = 3的类别

wine <- cut(wine_df$Wine, breaks=c(1,2,3), labels=c("A", "B", "C"))

Error in cut.default(wine_df$Wine, breaks = c(1, 2, 3), labels = c("A",  : 
  lengths of 'breaks' and 'labels' differ

但继续出现此错误:

Error in cut.default(wine_df$Wine, breaks = c(1, 2, 3), labels = c("A",  : 
  lengths of 'breaks' and 'labels' differ

任何人都可以支持这个问题吗?

3 个答案:

答案 0 :(得分:3)

我们可以使用LETTERS并相应地提取值

输入

x <- rep(1:3, 1:3)

输出

LETTERS[x]
#[1] "A" "B" "B" "C" "C" "C"

这里的重点是我们可以使用x来按位置提取另一个向量的值。

如果目标是更改1 = x,2 = y和3 = z(或其他任何值),我们可以做

c("x", "y", "z")[x]
#[1] "x" "y" "y" "z" "z" "z"

感谢@ zx8754的有用评论。

答案 1 :(得分:3)

处理R中类别变量的一种方法是通过因子。从帮助(?factor):

  

函数factor用于将向量编码为因子(术语   “类别”和“枚举类型”也用作因素)。如果   参数ordered为TRUE,则假定因子水平是有序的。   为了与S兼容,还有一个函数ordered

像这样,您可以将任意字符串分配为因子级别:

levels <- factor(c("category a", "category b", "category c"))
rep(1:3, 2)
[1] 1 2 3 1 2 3
levels[rep(1:3, 2)]
[1] category a category b category c category a category b category c
Levels: category a category b category c

当然,您也可以像这样分配“ A”,“ B”和“ C”:

levels <- factor(c("A", "B", "C"))
rep(1:3, 2)
[1] 1 2 3 1 2 3
levels[rep(1:3, 2)]
[1] A B C A B C
Levels: A B C

答案 2 :(得分:3)

您可以使用cut正确分配breaks。阅读?cut

cut(x, 0:3, c("a", "b", "c"))

#[1] a b b c c c
#Levels: a b c

使用了@markus的数据

x <- rep(1:3, 1:3)