How to extract columns of a data frame in R using dplyr package?

R ProgrammingServer Side ProgrammingProgramming

Example

> x <- seq(0, 20, by = 1)
> y <- dnorm(x, mean = 5, sd = 1)
> z <- dbinom(x, size=100, p=0.5)
> df<-data.frame(x,y,z)

Let’s say we want to extract columns y and z. It can be done in two ways as follows −

First

> library(dplyr)
> df %>%
select(y,z)
y z
1 1.486720e-06 7.888609e-31
2 1.338302e-04 7.888609e-29
3 4.431848e-03 3.904861e-27
4 5.399097e-02 1.275588e-25
5 2.419707e-01 3.093301e-24
6 3.989423e-01 5.939138e-23
7 2.419707e-01 9.403635e-22
8 5.399097e-02 1.262774e-20
9 4.431848e-03 1.467975e-19
10 1.338302e-04 1.500596e-18
11 1.486720e-06 1.365543e-17
12 6.075883e-09 1.117262e-16
13 9.134720e-12 8.286361e-16
14 5.052271e-15 5.609229e-15
15 1.027977e-18 3.485735e-14
16 7.694599e-23 1.998488e-13
17 2.118819e-27 1.061697e-12
18 2.146384e-32 5.246031e-12
19 7.998828e-38 2.419003e-11
20 1.096607e-43 1.043991e-10
21 5.530710e-50 4.228163e-10

Second

> select(df,y,z)
y z
1 1.486720e-06 7.888609e-31
2 1.338302e-04 7.888609e-29
3 4.431848e-03 3.904861e-27
4 5.399097e-02 1.275588e-25
5 2.419707e-01 3.093301e-24
6 3.989423e-01 5.939138e-23
7 2.419707e-01 9.403635e-22
8 5.399097e-02 1.262774e-20
9 4.431848e-03 1.467975e-19
10 1.338302e-04 1.500596e-18
11 1.486720e-06 1.365543e-17
12 6.075883e-09 1.117262e-16
13 9.134720e-12 8.286361e-16
14 5.052271e-15 5.609229e-15
15 1.027977e-18 3.485735e-14
16 7.694599e-23 1.998488e-13
17 2.118819e-27 1.061697e-12
18 2.146384e-32 5.246031e-12
19 7.998828e-38 2.419003e-11
20 1.096607e-43 1.043991e-10
21 5.530710e-50 4.228163e-10
raja
Published on 06-Jul-2020 13:01:50
Advertisements