How to extract a single column of an R data frame as a data frame?

R ProgrammingServer Side ProgrammingProgramming

Generally, we extract columns as a vector from an R data frame but sometimes we might need a column as a data frame, therefore, we can use as.data.frame to extract columns that we want to extract as a data frame with single square brackets. The purpose behind this could be merging the column with another data frame.

Example

Consider the below data frame −

set.seed(9)
x1<-rnorm(20)
x2<-rnorm(20,0.2)
x3<-rnorm(20,0.5)
x4<-rnorm(20,2.5)
x5<-rpois(20,5)
x6<-runif(20,2,5)
df<-data.frame(x1,x2,x3,x4,x5,x6)
df

Output

      x1       x2       x3       x4       x5       x6
1 -0.76679604 1.95699294 -0.30845634 2.7812222 5 3.087890
2 -0.81645834 0.38225214 -1.51938169 1.2972914 8 3.559316
3 -0.14153519 -0.06688875 -0.23872407 2.9651637 3 2.710724
4 -0.27760503 1.12642163 0.88288656 2.8520164 8 3.417152
5 0.43630690 -0.49333188 2.23086367 1.9101438 5 2.520602
6 -1.18687252 2.88199007 0.29691805 1.6464000 8 4.958743
7 1.19198691 0.42252448 -0.49639735 2.2532679 8 4.302067
8 -0.01819034 -0.50667241 -0.80653629 4.0393386 6 3.447421
9 -0.24808460 0.61721325 -0.49783160 3.0460777 2 2.992220
10 -0.36293689 0.56955678 -0.06502873 4.0649619 4 2.563962
11 1.27757055 -0.71376435 2.25205784 2.7496702 5 3.204598
12 -0.46889715 -0.11691475 -0.04777135 0.5375814 4 2.962441
13 0.07105410 1.24905921 -0.35852571 1.6909398 7 2.752308
14 -0.26603845 0.36811181 0.54929453 2.0013149 5 3.582086
15 1.84525720 0.23144021 0.29995552 2.8051218 3 4.365315
16 -0.83944966 -0.81033054 -0.60395445 2.2107928 3 3.258313
17 -0.07744806 0.58275153 0.74058804 3.9577142 2 2.204786
18 -2.61770553 -0.61969653 0.88111362 3.3737555 9 3.329696
19 0.88788403 0.56171109 2.73045895 1.5470440 7 4.025269
20 -0.70749145 0.29337136 1.69920239 2.4683245 4 4.254372

Extracting some columns as a separate data frames −

Example

x2 <-as.data.frame(df[,2])
x2

Output

df[, 2]
1 1.95699294
2 0.38225214
3 -0.06688875
4 1.12642163
5 -0.49333188
6 2.88199007
7 0.42252448
8 -0.50667241
9 0.61721325
10 0.56955678
11 -0.71376435
12 -0.11691475
13 1.24905921
14 0.36811181
15 0.23144021
16 -0.81033054
17 0.58275153
18 -0.61969653
19 0.56171109
20 0.29337136

Example

is.data.frame(x2)
[1] TRUE
x5 <-as.data.frame(df[,5])
x5
df[, 5]

Output

1 5
2 8
3 3
4 8
5 5
6 8
7 8
8 6
9 2
10 4
11 5
12 4
13 7
14 5
15 3
16 3
17 2
18 9
19 7
20 4

Example

is.data.frame(x5)
[1] TRUE
x3 <-as.data.frame(df[,3])
x3
df[, 3]

Output

1 -0.30845634
2 -1.51938169
3 -0.23872407
4 0.88288656
5 2.23086367
6 0.29691805
7 -0.49639735
8 -0.80653629
9 -0.49783160
10 -0.06502873
11 2.25205784
12 -0.04777135
13 -0.35852571
14 0.54929453
15 0.29995552
16 -0.60395445
17 0.74058804
18 0.88111362
19 2.73045895
20 1.69920239
is.data.frame(x3)
[1] TRUE
raja
Published on 21-Aug-2020 11:54:11
Advertisements