0

I would like to extract all columns for which the values are numeric from a dataframe, for a large dataset.

#generate mixed data
dat <- matrix(rnorm(100), nrow = 20)
df <- data.frame(letters[1 : 20], dat)

I was thinking of something along the lines of:

numdat <- df[,df == "numeric"]

That however leaves me without variables. The following gives an error.

dat <- df[,class == "numeric"]
Error in class == "numeric" : 
comparison (1) is possible only for atomic and list types

What should I do instead?

Tom
  • 2,173
  • 1
  • 17
  • 44

1 Answers1

2

use sapply

numdat <- df[,sapply(df, function(x) {class(x)== "numeric"})]
K.Hua
  • 769
  • 4
  • 20