将因子转换为数字而不丢失信息 R (as.numeric() 似乎不起作用)
有关 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
当我转换级别为 4 的因子时, , 8,使用 as.numeric() 将 10 和 15 转换为定量变量,每个数字都会转换为排名,并且原始值会丢失。
如何获取级别为 10、15、4 和 8 的向量“blah.new”,并将其转换为数值 10、15、4 和 8?
(这个问题的出现是因为一个数据集,其中一个定量变量被 read.table() 读取为一个因素)
谢谢!!!!
*****更新:弄清楚******
blah.new1<-as.numeric(as.character(blah.new))
但是,我想知道 as.numeric() 的文档中哪里说该函数将参数转换为排名列表?
Possible Duplicate:
R - How to convert a factor to an integer\numeric in R without a loss of information
The following fact about the as.numeric() function has been brought to my attention
> 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
When I convert a factor with levels 4, 8, 10, and 15 to a quantitative variable using as.numeric(), every number is converted to a ranking, and the original values are lost.
How do I take the vector 'blah.new' that has levels 10,15, 4, and 8, and convert it to the numeric values 10, 15, 4, and 8?
(This issue has arisen because of a dataset where a quantitative variable is read by read.table() to be a factor)
Thank you!!!!
*****Update: FIGURED IT OUT******
blah.new1<-as.numeric(as.character(blah.new))
However, I am wondering where in documentation for as.numeric() does it say that this function converts arguments into a list of rankings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,因子由指数和水平组成。当你与因素作斗争时,这一事实非常重要。
例如,
这里
z
有 4 个元素。索引按顺序为
2、1、2、3
。级别与每个索引相关联:1 -> b、2→ c,3-> d.
然后,
as.numeric
将因子的索引部分简单地转换为数字。as.character
处理索引和级别,并生成由其级别表示的字符向量。?as.numeric
表示因子由默认方法处理。First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
here,
z
has 4 elements.The index is
2, 1, 2, 3
in that order.The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then,
as.numeric
converts simply the index part of factor into numeric.as.character
handles the index and levels, and generates character vector expressed by its level.?as.numeric
says that Factors are handled by the default method.