如何在保留R中的数字的同时将因子变量转换为数字 [英] How to convert a factor variable to numeric while preserving the numbers in R
问题描述
我想通过变量ICPSR合并到数据集,但是由于ICPSR是因素,我不得不将其更改为数值变量.因此,我进行了数值计算,之后,我的ICPSR已更改为完全不同的值.我用谷歌搜索,发现我需要使用as.numeric(level(dv $ ICPSR)).但这只会产生唯一的值,而不是每个值.所以我想知道如何保存每个值并将其更改为可合并的数值.
I wanted to merge to dataset by a variable ICPSR, but since the ICPSR was factor I had to change it to numeric variable. So I did as.numeric and after doing that, my ICPSR has been changed to a totally different values. I googled and found I need to use as.numeric(level(dv$ICPSR)). But it only turns out unique values not every value. So I was wondering how can I preserve every value and change it to merge-able numeric values.
提前谢谢!
ICPSR session dv
1:1 15245 103 0.75
1:2 13003 103 0.00
1:3 14620 103 0.25
1:4 29105 103 0.00
1:5 29104 103 0.00
1:6 14414 103 0.25
dv$ICPSR<-as.numeric(dv$ICPSR)
head(dv)
ICPSR session dv
1:1 202 103 0.75
1:2 27 103 0.00
1:3 85 103 0.25
1:4 281 103 0.00
1:5 280 103 0.00
1:6 68 103 0.25
推荐答案
dv$ICPSR <- as.numeric(as.character(dv$ICPSR))
将因子转换为字符向量,然后再将其转换为数字向量.
Transform your factor to a character vector before transforming it into a numeric vector.
这篇关于如何在保留R中的数字的同时将因子变量转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!