2014-02-26 45 views
2

我已導入HTML表格到[R導入HTML表格

require(XML) 
u='http://www.ininternet.org/calorie.htm' 
tables = readHTMLTable(u) 
my.table=tables[[9]] 
View(my.table) 

但現在我有問題,當我要分析的數據和應用的任何功能,例如

> mean(PROTEINE) 
Warning message: 
In mean.default(PROTEINE) : 
    argument is not numeric or logical: returning NA 

請告訴我如何導入表格,以便我可以正確分析數據。

+0

看看你的對象與'STR(my.table)',它會告訴你的重要的詳細信息,請桌子快速和容易。 – SlowLearner

回答

3

你試圖計算「因子」類型變量的均值:

> lapply(my.table, class) 
$ALIMENTO 
[1] "factor" 

$PROTEINE 
[1] "factor" 

$GRASSI 
[1] "factor" 

$CARBOIDRATI 
[1] "factor" 

$CALORIE 
[1] "factor" 

$COLESTEROLO 
[1] "factor" 

你需要將其轉換爲數字第一。考慮:

tmp <- as.numeric(as.character(my.table$PROTEINE)) 
mean(tmp) 
## [1] 10.81395 

有關說明,請參閱this question and answer

2

它們都是重要的因素,將其更改爲字符和數字是這樣的:

my.table[,1] <- sapply(my.table[,1], as.character) 
my.table[,2:6] <- sapply(my.table[,2:6], function(x) as.numeric(as.character(x)) 

還是在原來的讀入,指定stringsAsFactors=F。但是,這不是完美的,因爲它使得一切的性格,所以你仍然需要轉換爲數字

tables = readHTMLTable(u,stringsAsFactors=F) 
my.table[,2:6] <- sapply(my.table[,2:6], as.numeric)