Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements