【问题标题】:Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work) [duplicate]在不丢失信息的情况下将因子转换为数字 R(as.numeric() 似乎不起作用)[重复]
【发布时间】:2011-11-28 12:50:39
【问题描述】:

可能重复:
R - How to convert a factor to an integer\numeric in R without a loss of information

以下关于 as.numeric() 函数的事实引起了我的注意

> blah<-c("4","8","10","15")
> blah
[1] "4"  "8"  "10" "15"
> blah.new<-as.factor(blah)
> blah.new
[1] 4  8  10 15
Levels: 10 15 4 8
> blah.new1<-as.numeric(blah.new)
> blah.new1
[1] 3 4 1 2

当我使用 as.numeric() 将级别为 4、8、10 和 15 的因子转换为定量变量时,每个数字都会转换为排名,而原始值会丢失。

如何获取具有级别 10、15、4 和 8 的向量“blah.new”,并将其转换为数值 10、15、4 和 8?

(这个问题的出现是因为一个数据集,其中一个定量变量被 read.table() 读取为一个因素)

谢谢!!!!

*****更新:想通了******

blah.new1<-as.numeric(as.character(blah.new))

但是,我想知道 as.numeric() 的文档中的哪个位置说此函数将参数转换为排名列表?

【问题讨论】:

  • 这在?factor警告部分中记录
  • 但它不在我正在翻阅的任何一本 R 书籍中,而且它现在确实让我陷入了困境。

标签: r r-factor


【解决方案1】:

首先,因子由指数和水平组成。当您与因素斗争时,这一事实非常重要。

例如,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

这里,z 有 4 个元素。
索引按此顺序为2, 1, 2, 3
level 与每个 index 相关联:1 -> b、2 -> c、3 -> d。

然后,as.numeric 将 factor 的 index 部分简单地转换为数字。
as.character 处理索引和级别,并生成由其 level 表示的字符向量强>。

?as.numeric 表示因子由默认方法处理

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2012-04-14
    • 2015-01-10
    相关资源
    最近更新 更多