在R中,如何通过不同的标签设置和保留自定义级别? [英] in R, how to set and retain custom levels in factor with different labels?
问题描述
在R中,如何设置和保留具有不同标签的自定义水平?
in R, how to set and retain custom levels in factor with different labels ?
也就是说,我想在一个因子的级别中设置自定义数字,这些数字值-要保留的整数而不是转换为"1、2、3等".
That is, I want to set custom numbers in the levels of a factor, and these numerical values - integers to be retained and not converted to "1, 2, 3 etc.".
我知道一种解决方案是将这些权重设置为标签",但是随后我将丢失该因子的标签".
I know that one solution is to set these weights as Labels, but then I will missing the "labels" of the factor.
不保留因素之间的加权"距离.在R中,是否可以使用单个变量来实现类似的目标?
The "weighted" distance between factors is not retained. Is it possible in R, to achieve something like this, using a single variable ?
例如:
age_f <- factor( c(1, 10, 100), levels = c( 1, 10, 100 ), labels = c( "baby", "child", "old" ), ordered = T )
levels(age_f)
[1] "baby" "child" "old"
labels(age_f)
[1] "1" "2" "3"
labels(levels(age_f))
[1] "1" "2" "3"
as.numeric(age_f)
[1] 1 2 3
Desired output:
as.numeric(age_f)
[1] 1 10 100
如果在R因子中不存在此参数,是否容易通过自定义函数产生这样的结果?
If this does not exists in R factors, it is easy to produce such result by a custom function?
推荐答案
您可以为此使用 labelled
包.
library(labelled)
labelled(c(1, 10, 100), c(baby = 1, child = 10 , old = 100))
<Labelled double>
[1] 1 10 100
Labels:
value label
1 baby
10 child
100 old
如果以后要将其转换为常规因子,则可以使用 to_factor
.
If you later want to convert it into a regular factor you can use to_factor
.
这篇关于在R中,如何通过不同的标签设置和保留自定义级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!