Skip to content

Check if data frame column is numeric

5 messages · Mark Heckmann, Henrique Dallazuanna, Wacek Kusnierczyk +2 more

#
Hi R-users,

I want to apply a function to each column of a data frame that is numeric.
Thus I tried to check it for each column first:
A60       A64      A66a       A67       A71      A75a       A80
A85       A91       A95       A96       A97       A98       A99 
    FALSE     FALSE     FALSE     FALSE     FALSE     FALSE     FALSE
FALSE     FALSE     FALSE     FALSE     FALSE     FALSE     FALSE

I get only FALSE results although the variables are numeric. When I try the
following it works:
[1] TRUE

What am I doing wrong?

TIA
Mark
#
from ?apply:

" If 'X' is not an array but has a dimension attribute, 'apply' attempts
to coerce it to an array via as.matrix' if it is two-dimensional (e.g.,
data frames) or via 'as.array'."

if any of the columns in your dataframe is not numeric, apply will try
to coerce all of them to the least common supertype, and you'll get
FALSE for each column;  this is not the case with sapply.

d1 = data.frame(x=numeric(10), y=numeric(10))
d2 = data.frame(d1, z=character(10))

apply(d1, 2, is.numeric)
# TRUE TRUE
apply(d1, 2, function(x) is.numeric(x))
# same as above, redundant code
sapply(d1, is.numeric)
# TRUE TRUE

apply(d2, 2, is.numeric)
# FALSE FALSE FALSE
sapply(d2, is.numeric)
# TRUE TRUE FALSE

vQ
Mark Heckmann wrote:
#
... and an addendum

Hadley Wickham's plyR package attempts to redress these (nevertheless
documented) apparent inconsistencies in the *apply family of functions by
handling everything in a more consistent intuitive manner. You may wish to
use those instead of the base R *apply functions.

-- Bert Gunter
Genentech



-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Henrique Dallazuanna
Sent: Tuesday, December 16, 2008 9:32 AM
To: Mark Heckmann
Cc: r-help at r-project.org
Subject: Re: [R] Check if data frame column is numeric

Try:

sapply(df, is.numeric)
On Tue, Dec 16, 2008 at 1:25 PM, Mark Heckmann <mark.heckmann at gmx.de> wrote:

            
the

  
    
#
On Tue, 16 Dec 2008 16:25:07 +0100, Mark Heckmann <mark.heckmann at gmx.de> wrote:

            
colwise(), numcolwise() and catcolwise() in plyr package  turn a function that operates on vectors into one that operates on columns of data frame:

in your case it would be :

numcolwise(your.fun)(your.data.frame)

Vitalie.