将数据框列类从因子更改为数字,而不更改数据框中的值

时间:2012-08-01 12:19:15

标签: r dataframe transform numeric r-factor

  

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

我对data.frame中的因子列有疑问。我想将因子转换为数字类,并尝试不同的东西,但我的结果有点奇怪。我有这样的数据框:

head(tag)
                   KI_1  KI_2 KI_4 KI_5  KI_6  WT_1  WT_2  WT_3 WT_4 WT_6
AAAAAAAAAAAAAAAAA 32158 26474 4879 7657 23420 27362 33745 25479 5635 7500
AAAAAAAAAAAAAAAAC  1593  1287  287  419  1136  1370  1670  1173  318  443
AAAAAAAAAAAAAAAAG   366   244   63   86   193   313   329   258   74   81
AAAAAAAAAAAAAAAAT 12262  9067  611 1956  8869 10324 11679  9507 2089 1896
AAAAAAAAAAAAAAACA    68    57   16   28    49    70    75    46   27   22
AAAAAAAAAAAAAAACC   197   142   28   50   161   178   235   180   42   56

sapply(tag, class)
    KI_1     KI_2     KI_4     KI_5     KI_6     WT_1     WT_2     WT_3    WT_4     WT_6 
"factor" "factor" "factor" "factor" "factor" "factor" "factor" "factor" "factor" "factor" 

我想将de class“factor”更改为class“numeric”。我认为下面的解决方案很好,但是如果你查看我创建的表,那么值就会改变。有没有办法防止这种变化的价值?或另一种获取数字数据框的解决方案?

谢谢

tagwise1 <- transform(tag, KI_1 = as.numeric(KI_1), KI_2 = as.numeric(KI_2), KI_4 = as.numeric(KI_4), KI_5 = as.numeric(KI_5), KI_6 = as.numeric(KI_6), WT_1 = as.numeric(WT_1),WT_2 = as.numeric(WT_2),WT_3 = as.numeric(WT_3),WT_4 = as.numeric(WT_4),WT_6 = as.numeric(WT_6))
sapply(tagwise1, class)
     KI_1      KI_2      KI_4      KI_5      KI_6      WT_1      WT_2      WT_3      WT_4      WT_6
"numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" "numeric" 

head(tagwise1)
                  KI_1 KI_2 KI_4 KI_5 KI_6 WT_1 WT_2 WT_3 WT_4 WT_6
AAAAAAAAAAAAAAAAA 1661 1107 1529 2330  942 1379 1609 1053 2056 2111
AAAAAAAAAAAAAAAAC  692  310 1073 1711  148  442  721  184 1464 1585
AAAAAAAAAAAAAAAAG 1821 1020 1750 2485  736 1548 1584 1070 2341 2195
AAAAAAAAAAAAAAAAT  291 2319 1725  881 2203   44  212 2359  976  779
AAAAAAAAAAAAAAACA 2515 1830  519 1329 1592 2444 2498 1617 1294  955
AAAAAAAAAAAAAAACC 1013  427 1049 1882  540  816 1179  687 1758 1815

0 个答案:

没有答案