Python的R等价物是什么;将分类变量转换为整数级别的代码?
在python中,可以使用.cat.code为变量生成分类代码,例如Python的R等价物是什么;将分类变量转换为整数级别的代码?,r,numeric,categorical-data,r-factor,R,Numeric,Categorical Data,R Factor,在python中,可以使用.cat.code为变量生成分类代码,例如 df['col3'] = df['col3'].astype('category').cat.code 如何在R中实现这一点?进一步充实@Sid29: python方法函数.cat.code提取因子级别的数值表示。R中的等效值为: a <- factor(c("good", "bad", "good", "bad", "terri
df['col3'] = df['col3'].astype('category').cat.code
如何在R中实现这一点?进一步充实@Sid29: python方法函数
.cat.code
提取因子级别的数值表示。R中的等效值为:
a <- factor(c("good", "bad", "good", "bad", "terrible"))
as.numeric(a)
[1] 2 1 2 1 3
a也许更清楚的做法是:
# if you want numeric code for every value
a <- factor(c("good", "bad", "good", "bad", "terrible"))
as.integer(a)
# 2 1 2 1 3
# unique labels and the values for them
setNames(levels(a), seq_along(levels(a)))
# 1 2 3
# "bad" "good" "terrible"
#如果您希望每个值都有数字代码
a如果我正确理解.cat.code
,您需要类别的数字表示。如果这是你的因素:a@Amar是的,你能写下来作为答案吗?我会接受ir:-)这有点奇怪。不需要将名称设置为级别,也不需要澄清情况。此外,还不清楚您是否理解这对a
对象没有任何影响。@42-更像是表示以下是值的基本数字代码。有更好的方法将它们显示在一起吗?如果你想显示的是levels(a)
,为什么不直接使用levels(a)
?或者(奇怪的是)甚至c(a)
。事实证明,在R中没有c.factor
,使用c
与as.vector
或您提供的as.integer
具有相同的效果。因子的翻转很奇怪。为什么as.numeric(标签(a))[a]
?as.numeric(a)
不是更简单地做同样的事情吗?