This, you will use sapply
with the is.numeric
function. In summary, sapply
will apply to every variable (column) of your data.frame the is.numeric
function to know if that is a numeric variable.
Generating a basis for demonstration:
df <- data.frame(numeric1 = 1:10,
factor = factor(c("a", "b")),
character = "texto",
numeric2 = 10:1,
logical = TRUE ,
stringsAsFactors = FALSE)
str(df)
$ numeric1 : int 1 2 3 4 5 6 7 8 9 10
$ factor : Factor w/ 2 levels "a","b": 1 2 1 2 1 2 1 2 1 2
$ character: chr "texto" "texto" "texto" "texto" ...
$ numeric2 : int 10 9 8 7 6 5 4 3 2 1
$ logical : logi TRUE TRUE TRUE TRUE TRUE TRUE ...
Using sapply
with is.numeric
to generate a vector indicating which columns are numeric:
numericas <- sapply(df, is.numeric)
numericas
numeric1 factor character numeric2 logical
TRUE FALSE FALSE TRUE FALSE
Now you can use this vector to filter the data.frame:
df[,numericas]
numeric1 numeric2
1 1 10
2 2 9
3 3 8
4 4 7
5 5 6
6 6 5
7 7 4
8 8 3
9 9 2
10 10 1