Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting subset of the data frame in R

Tags:

r

Suppose I read a csv file into a data frame called "d". I wish to print the last 2 rows of this data frame. I tried the below but it is printing all the content starting from n-1. Can someone help me understand this behavior please?

> n<-nrow(d)
> n
[1] 153
> subset(d[n:n-1,])
like image 266
Aravind Yarram Avatar asked Jan 08 '13 06:01

Aravind Yarram


2 Answers

You can just use tail

  tail(d, 2)

Will give the last two rows.

like image 132
mnel Avatar answered Sep 21 '22 23:09

mnel


@mnel is correct that using tail() would probably be the easiest, however I think that your confusion has to do with how subset() and indexing work in general. In your example be mindful of how you index matrices and data.frames since

d[(n:n - 1), ]

is not the same as

d[n:(n-1), ]

so check the difference carefully since the order of operations are important to understand. The subset() function also indexes based on a logical indicator and has the form

 subset(object, subset = logicalvector)

where the logical vector gives the rows that you want to extract. See ?subset for more detail.

like image 39
philchalmers Avatar answered Sep 24 '22 23:09

philchalmers