1

让我们www.exampleweb.com成为一个有这样数据的网站:

...  
-3.7358293e+000
7.6062331e-001
6.0701401e+000
-1.6897975e+000
-2.1088811e+000
2.7172791e+000
-2.5477626e+000
...

1 列,1000 行。
我通过两种方式从这个网站获取数据:
1。

con = url("www.exampleweb.com")  
data_from_html <- readLines(con)  
close(con) 

现在需要转换数据,因为

str(data_from_html)
chr [1:1000] " -2.9735888e+000" " -1.4757566e+000" "  8.6980880e-001" "  4.9502553e+000" ...  

所以:

converted <- as.numeric(data_from_html)

复制 (ctrl+a) 整个网站,然后粘贴到 .txt 文件中。另存为“my_data.txt”。

data_from_txt <- read.table("my_data.txt")  

现在,当我使用

summary(converted)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
-16.2800  -1.5030  -0.0598  -0.1809   1.2220  13.0100   

但另一方面:

summary(data_from_txt)
       V1          
 Min.   :-16.2789  
 1st Qu.: -1.5026  
 Median : -0.0598  
 Mean   : -0.1809  
 3rd Qu.:  1.2217  
 Max.   : 13.0112  

我无法决定哪个更好,但我觉得在从 char 转换为 numeric 时会丢失一些数据。我不知道如何防止它。我什至检查了这些变量的头/尾,但它们的值相同:

head(converted)

[1] -2.9735888 -1.4757566  0.8698088  4.9502553 -4.3059115  0.9745958
> tail(converted)
[1] -3.007217 -4.600345 -3.740255  2.579664 -2.233819 -1.028491    

head(data_from_txt)
          V1
1 -2.9735888
2 -1.4757566
3  0.8698088
4  4.9502553
5 -4.3059115
6  0.9745958
> tail(data_from_txt)
            V1
995  -3.007217
996  -4.600345
997  -3.740255
998   2.579664
999  -2.233819
1000 -1.028491  

如何处理?这是否意味着我永远不应该在网络上抓取数据?如果我由于某种原因无法创建 .txt 文件怎么办?也许我开玩笑需要更好的数据转换方法?

4

0 回答 0