1

可能重复:
如何在不丢失信息的情况下将因子转换为整数\数字

我对 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
4

0 回答 0