2016-05-16 205 views
-2

我有一個數字,整數和字符串的數據框。我想檢查哪些列是整數,我做is.integer()在R中的工作原理

raw<-read.csv('./rawcorpus.csv',head=F) 
ints<-sapply(raw,is.integer) 

無論如何,這給了我所有的虛假。所以我必須做一點改變

nums<-sapply(raw,is.numeric) 
ints2<-sapply(raw[,nums],function(col){return(!(sum(col%%1)==0))}) 

第二種情況工作正常。我的問題是:什麼是實際檢查'is.integer'功能?

+0

它檢查一個向量是否是'integer'類型。如果它返回'FALSE',你的data.frame列不是整數。嘗試'sapply(raw,class)'來查看列類。或者使用'str'。 – Roland

+0

'is.integer()'與'typeof()'的結果相關。請參閱幫助文件。 –

回答

3

默認情況下,R將所有數字存儲爲雙精度浮點,即numeric。三個有用的功能class,typeofstorage.mode會告訴你如何存儲一個值。嘗試:

x <- 1 
class(x) 
typeof(x) 
storage.mode(x) 

如果你想x是整數1,你應該後綴做 「L」

x <- 1L 
class(x) 
typeof(x) 
storage.mode(x) 

或者,您也可以通過施放數字爲整數:

x <- as.integer(1) 
class(x) 
typeof(x) 
storage.mode(x) 

is.integer函數檢查存儲模式是否爲整數。比較

is.integer(1) 
is.integer(1L) 

你應該知道,有些功能實際上返回numeric,即使你希望它返回integer。這些包括round,floor,ceiling和mod運算符%%

+0

'type.convert'可以很好的識別整數:'x < - read.table(text =「1 \ n2」); STR(X)'。如果OP在列中只有(只)整數,那麼它們應該在導入後作爲整數存儲。 – Roland

1

從R文件:

is.integer(x)如果x包含整數不會測試!爲此,請使用round,如示例中的函數is.wholenumber(x)。

所以在is.integer(x)中,x必須是一個向量,如果這個包含整數,你會變成true。在你的第一個例子中,參數是一個數字,而不是一個向量

希望幫助

來源:https://stat.ethz.ch/R-manual/R-devel/library/base/html/integer.html