Extracting subset of the data frame in R

前端 未结 4 1635
一向
一向 2021-01-12 23:43

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 f

相关标签:
4条回答
  • 2021-01-13 00:16

    I would use: tail(d, 2) or d[(n-1):n, ] Hope it helps

    0 讨论(0)
  • 2021-01-13 00:23

    You can just use tail

      tail(d, 2)
    

    Will give the last two rows.

    0 讨论(0)
  • 2021-01-13 00:36

    @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.

    0 讨论(0)
  • 2021-01-13 00:37

    This is working for me ...

    d <- matrix(1:10,nrow=5)
    d
         [,1] [,2]
    [1,]    1    6
    [2,]    2    7
    [3,]    3    8
    [4,]    4    9
    [5,]    5   10
    
    d <- as.data.frame(d)
    d
      V1 V2
    1  1  6
    2  2  7
    3  3  8
    4  4  9
    5  5 10
    
    n <- nrow(d)
    > n
    [1] 5
    d[n:(n-1),] ## Specifying the number of the row inside the brackets.
     V1 V2
    5  5 10
    4  4  9
    
    d[n:n-1,] ## without brackets it will do 5:5 -1 = 4, so printing only the fourth row
      V1 V2
    4  4  9
    
    0 讨论(0)
提交回复
热议问题