0 votes
1 view
in R Programming by (6.5k points)

Suppose, you have a data.frame like this:

x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])

How would you select only those columns in x that are numeric?

1 Answer

0 votes
by (25.3k points)

To select only numeric rows from a data frame, you can use the select_if() function from the dplyr package as follows:

x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])

z <- select_if(x, is.numeric) 

z

Output:

   v1 v2 v3

1   1  1  1

2   2  2  2

3   3  3  3

4   4  4  4

5   5  5  5

6   6  6  6

7   7  7  7

8   8  8  8

9   9  9  9

10 10 10 10

11 11 11 11

12 12 12 12

13 13 13 13

14 14 14 14

15 15 15 15

16 16 16 16

17 17 17 17

18 18 18 18

19 19 19 19

20 20 20 20

The select_if() function returns the selected columns as a data frame,i.e.:

str(z)

'data.frame': 20 obs. of  3 variables:

 $ v1: int  1 2 3 4 5 6 7 8 9 10 ...

 $ v2: int  1 2 3 4 5 6 7 8 9 10 ...

$ v3: int  1 2 3 4 5 6 7 8 9 10 ...

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...