Hashim
Hashim

Reputation: 327

Test condition in all the columns of a data frame

I have a data frame and I check if the all the columns of the data frame contain numeric values.

   V1         V2         V3
1  114        9.078186  1.6310523
2  116        8.228931  1.6405415
3  117        8.043536  1.6625413
4  118        6.179346  0.8489116

I use

sapply(df,is.numeric) 

this returns

    V1            V2            V3
   TRUE            TRUE          TRUE

Now how do I check if all the columns are numeric? I'm looking for something like:

if(sapply(df,is.numeric)==TRUE)
print(" All are Numeric")

But it check only one condition , as the length of vector is more than one so it through a warning

Warning message:
In if (sapply(df, is.numeric) == TRUE):
  the condition has length > 1 and only the first element will be used

Upvotes: 2

Views: 2386

Answers (1)

Feng Mai
Feng Mai

Reputation: 3109

The sapply returns a True/False vector, you can treat the entries as 1/0 and check if the sum is equal to the total number of columns.

if(sum(sapply(df,is.numeric))==ncol(df))
  print(" All are Numeric")

Or you can use the all() function

if(all(sapply(df,is.numeric)))
  print(" All are Numeric")

Upvotes: 4

Related Questions