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
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
任何人都可以支持这个问题吗?
答案 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)