Wednesday 8 July 2015

R: Subsetting ( vectors, lists)

R provides different operators to get subsets of R objects like vector, list, data frame.

“[“ (Single bracket)

‘[‘ Operator is used to extract the elements of an R Object.
> vector1 <- c(1, 25, 23, 2, 32, 54, 67, 98, 54, 3)
> 
> vector1[4]
[1] 2
> vector1[1:5]
[1]  1 25 23  2 32


vector[1:5] is used to extract the elements of vector from index 1 to 5. You can apply logical indexing also.
> vector1[vector1 > 50]
[1] 54 67 98 54
> 
> vector1[vector1 < 50]
[1]  1 25 23  2 32  3

“vector1[vector1 > 50]” : Returns all elements of vector, which are greater than 50.

[[ (Double bracket)

It is used to extract the elements of a list (or) data frame. It is only used to extract single element of list (or) data frame.
> list1 <-  list(data1=1:5, data2=6:10, data3=11:15)
> list1
$data1
[1] 1 2 3 4 5

$data2
[1]  6  7  8  9 10

$data3
[1] 11 12 13 14 15

> 
> list1[[1]]
[1] 1 2 3 4 5
> 
> list1[1]
$data1
[1] 1 2 3 4 5
>
> list1[[1]][4]
[1] 4
> list1[[2]][4]
[1] 9
> list1[[3]][4]
[1] 14

list1[1]
Above statement returns the list that contains sequence 1 to 4.

list1[[1]]
 Above statement returns just the sequence.

list1[[1]][4]
Above statement returns 4th element of 1st member of the list list1.

list1[[2]][4]
Above statement returns 4th element of 2nd member of the list list1.


Use single square bracke “[“, to extract multiple elements of a list.
> list1[c(1, 3)]
$data1
[1] 1 2 3 4 5

$data3
[1] 11 12 13 14 15

> 
> list1[c(2, 1)]
$data2
[1]  6  7  8  9 10

$data1
[1] 1 2 3 4 5

“list1[c(1, 3)]” returns 1st and 3rd elements of the list list1.

$ Operator

It is similar to [[, used to extract elements of list (or) data frame by using name.
> list1
$data1
[1] 1 2 3 4 5

$data2
[1]  6  7  8  9 10

$data3
[1] 11 12 13 14 15

> 
> list1$data1
[1] 1 2 3 4 5
> 
> list1$data2
[1]  6  7  8  9 10
> 
> list1$data3
[1] 11 12 13 14 15


If you don’t remember the index, then $ operator is very useful, since you can extract information by using name.






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment