- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select only numeric columns from an R data frame?
The easiest way to do it is by using select_if function of dplyr package but we can also do it through lapply.
Using dplyr
> df <- data.frame(X1=1:10,X2=11:20,X3=21:30,X4=letters[1:10], X5=letters[11:20]) > df X1 X2 X3 X4 X5 1 1 11 21 a k 2 2 12 22 b l 3 3 13 23 c m 4 4 14 24 d n 5 5 15 25 e o 6 6 16 26 f p 7 7 17 27 g q 8 8 18 28 h r 9 9 19 29 i s 10 10 20 30 j t >library("dplyr") > select_if(df, is.numeric) X1 X2 X3 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 24 5 5 15 25 6 6 16 26 7 7 17 27 8 8 18 28 9 9 19 29 10 10 20 30
Using lapply
> numeric_only <- unlist(lapply(df, is.numeric)) > df[ , numeric_only] X1 X2 X3 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 24 5 5 15 25 6 6 16 26 7 7 17 27 8 8 18 28 9 9 19 29 10 10 20 30
- Related Articles
- How to extract only factor columns name from an R data frame?
- How to select only one column from an R data frame and return it as a data frame instead of vector?
- How to convert a data frame with categorical columns to numeric in R?
- How to find the correlation for data frame having numeric and non-numeric columns in R?
- How to standardize only numerical columns in an R data frame if categorical columns also exist?
- How to select columns of an R data frame that are not in a vector?
- How to standardize columns in an R data frame?
- How to select data frame columns based on their class in R?
- How to convert a character data frame to numeric data frame in R?
- How to reorder the columns in an R data frame?
- How to subset factor columns in an R data frame?
- How to concatenate numerical columns in an R data frame?
- Select columns of an R data frame and skip if does not exist.
- How to find the correlation matrix by considering only numerical columns in an R data frame?
- How to get list of all columns except one or more columns from an R data frame?

Advertisements