How to extract a particular value based on index from an R data frame column?


Sometimes we want to figure out which value lies at some position in an R data frame column, this helps us to understand the data collection or data simulation process. For example, if we have a data frame df that contain columns x, y, and z each with 5000 values then we can use df$x[[253]] to find which values lies at 253rd row in column x of data frame df.

Example

Consider the below data frame −

 Live Demo

set.seed(987)
x<-rnorm(20,521,30.7)
y<-rnorm(20,20,4.05)
z<-rnorm(20,31,1)
a<-rpois(20,8)
b<-rpois(20,10)
c<-rpois(20,2)
df<-data.frame(x,y,z,a,b,c)
df

Output

   x    y     z      a     b    c
1 519.2497 26.62916 31.48431 14 18 0
2 529.2888 16.46887 32.70400 5 5 1
3 547.8463 13.71248 29.73358 10 11 2
4 515.1564 22.82227 30.12065 6 5 5
5 554.7914 20.28892 32.52483 7 2 4
6 493.5616 15.45613 31.23513 14 10 3
7 491.6825 22.32123 30.81875 4 9 4
8 494.7252 18.33388 32.50834 8 13 1
9 486.8303 13.96303 30.71686 5 10 2
10 481.4361 18.60518 32.32576 13 9 3
11 544.2612 19.79058 32.56325 7 8 1
12 494.0999 23.56244 30.83515 4 14 3
13 574.9847 27.61496 29.30917 9 6 0
14 520.7027 27.62166 29.93995 10 12 0
15 507.2346 22.38830 31.16826 7 15 0
16 517.3553 22.60314 31.76175 6 9 2
17 507.0164 18.61279 31.86548 10 10 3
18 484.6791 24.74147 31.88115 5 6 5
19 507.0228 25.21739 32.09461 5 4 0
20 552.1552 16.49131 31.39587 5 7 2

Extracting values from column x using index −

df$x[[1]]
[1] 519.2497
df$x[[5]]
[1] 554.7914
df$x[[6]]
[1] 493.5616
df$x[[7]]
[1] 491.6825
df$x[[12]]
[1] 494.0999
df$x[[15]]
[1] 507.2346
df$x[[19]]
[1] 507.0228
df$x[[20]]
[1] 552.1552

Extracting values from column y using index −

df$y[[19]]
[1] 25.21739
df$y[[1]]
[1] 26.62916
df$y[[4]]
[1] 22.82227
df$y[[3]]
[1] 13.71248
df$y[[5]]
[1] 20.28892
df$y[[7]]
[1] 22.32123
df$y[[10]]
[1] 18.60518
df$y[[9]]
[1] 13.96303
df$y[[13]]
[1] 27.61496
df$y[[14]]
[1] 27.62166
df$y[[18]]
[1] 24.74147

Extracting values from column z using index:

df$z[[2]]
[1] 32.704
df$z[[5]]
[1] 32.52483
df$z[[10]]
[1] 32.32576
df$z[[15]]
[1] 31.16826
df$z[[20]]
[1] 31.39587
df$z[[17]]
[1] 31.86548

Extracting values from column a using index −

df$a[[20]]
[1] 5
df$a[[1]]
[1] 14
df$a[[10]]
[1] 13
df$a[[12]]
[1] 4
df$a[[5]]
[1] 7
df$a[[13]]
[1] 9
df$a[[17]]
[1] 10
df$a[[18]]
[1] 5
df$a[[19]]
[1] 5

Extracting values from column b using index −

df$b[[1]]
[1] 18
df$b[[5]]
[1] 2
df$b[[10]]
[1] 9
df$b[[15]]
[1] 15
df$b[[20]]
[1] 7

Extracting values from column c using index −

df$c[[3]]
[1] 2
df$c[[6]]
[1] 3
df$c[[9]]
[1] 2
df$c[[12]]
[1] 3
df$c[[15]]
[1] 0
df$c[[18]]
[1] 5

Updated on: 17-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements