emanuele
emanuele

Reputation: 2589

How is.integer() works in R

I have a data frame of numerics,integers and string. I would like to check which columns are integers and I do

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

anyway this gives me all false. So I have to make a little change

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

The second case works fine. My question is: what is actually checking the 'is.integer' function?

Upvotes: 0

Views: 4703

Answers (2)

Zheyuan Li
Zheyuan Li

Reputation: 73385

By default, R will store all numbers as double precision floating points, i.e., the numeric. Three useful functions class, typeof and storage.mode will tell you how a value is stored. Try:

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

If you want x to be integer 1, you should do with suffix "L"

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

Or, you can cast numeric to integers by:

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

The is.integer function checks whether the storage mode is integer or not. Compare

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

You should be aware that some functions actually return numeric, even if you expect it to return integer. These include round, floor, ceiling, and mod operator %%.

Upvotes: 6

AshkaliD
AshkaliD

Reputation: 299

From R documentation:

is.integer(x) does not test if x contains integer numbers! For that, use round, as in the function is.wholenumber(x) in the examples.

So in is.integer(x), x must be a vector and if that contains integer numbers, you will get true. In your first example, argument is a number, not a vector

Hope that helps

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

Upvotes: 1

Related Questions