as.numeric函数更改数据框中的值

时间:2014-04-01 15:38:55

标签: r sum numeric mean

我有一个包含速度测量的列,我需要将其更改为数字,以便我可以使用均值和求和函数。但是,当我转换它们时,值会发生很大变化。

为什么会这样?

这是我的数据最初的样子:

enter image description here

这是数据框的结构:

'data.frame':   1899571 obs. of  20 variables:
 $ pcd        : Factor w/ 1736958 levels "AB101AA","AB101AB",..: 1 2 3 4 5 6 6 7 7 8 
 $ pcdstatus  : Factor w/ 5 levels "Insufficient Data",..: 4 4 4 4 4 2 3 2 3 3 ...
 $ mbps2      : Factor w/ 3 levels "N","N/A","Y": 2 2 2 2 2 2 2 2 2 2 ...
 $ averagesp  : Factor w/ 301 levels ">=30","0","0.2",..: 301 301 301 301 301 301 301 
 $ mediansp   : Factor w/ 302 levels ">=30","0","0.1",..: 302 302 302 302 302 302 302 
 $ maxsp      : Factor w/ 301 levels ">=30","0","0.2",..: 301 301 301 301 301 301 301 
 $ nga        : Factor w/ 2 levels "N","Y": 1 2 1 1 1 1 1 2 2 2 ...
 $ connections: Factor w/ 119 levels "<3","0","1","10",..: 2 2 2 2 2 1 2 1 2 2 ...
 $ pcd2       : Factor w/ 1736958 levels "AB10 1AA","AB10 1AB",..: 1 2 3 4 5 6 6 7 7 8 
 $ pcds       : Factor w/ 1736958 levels "AB10 1AA","AB10 1AB",..: 1 2 3 4 5 6 6 7 7 8 
 $ oslaua     : Factor w/ 407 levels "","95A","95B",..: 374 374 374 374 374 374 374 
 $ x          : int  394251 394232 394181 394251 394371 394181 394181 394331 394331 
 $ y          : int  806376 806470 806429 806376 806359 806429 806429 806530 806530 
 $ ctry       : Factor w/ 4 levels "E92000001","N92000002",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ hro2       : Factor w/ 13 levels "","E12000001",..: 12 12 12 12 12 12 12 12 12 12 
 $ soa1       : Factor w/ 34381 levels "","E01000001",..: 32485 32485 32485 32485 
 $ dzone1     : Factor w/ 6507 levels "","E99999999",..: 128 128 128 128 112 128 128 
 $ soa2       : Factor w/ 7197 levels "","E02000001",..: 6784 6784 6784 6784 6784 6784 
 $ urindew    : int  9 9 9 9 9 9 9 9 9 9 ...
 $ soa1ni     : Factor w/ 892 levels "","95AA01S1",..: 892 892 892 892 892 892 892 892 

这是将我的变量转换为数字变量的代码。

 #convert individual columns to numeric variables  
 total$averagesp <- as.numeric(total$averagesp) 
 total$mediansp <- as.numeric(total$mediansp) 
 total$maxsp <- as.numeric(total$maxsp) 
 total$mbps2 <- as.numeric(total$mbps2)
 total$nga <- as.numeric(total$nga)
 total$connections <- as.numeric(total$connections)

但是之后我的所有数据都被夸大了,我有这个奇怪的输出:

enter image description here

非常感谢任何帮助 - 谢谢!

1 个答案:

答案 0 :(得分:6)

FAQ 7.10。基本上,当您在一个因子上使用as.numeric时,您将获得基础整数。常见问题解答有将其转换为字符串所代表的数字的方法。