簡體   English   中英

在R中提取數據幀的子集

[英]Extracting subset of the data frame in R

假設我將csv文件讀入名為“d”的數據框中。 我希望打印此數據框的最后兩行。 我嘗試了下面但它打印的所有內容都是從n-1開始的。 有人可以幫我理解這種行為嗎?

> n<-nrow(d)
> n
[1] 153
> subset(d[n:n-1,])

你可以用尾巴

  tail(d, 2)

將給出最后兩行。

@mnel是正確的,使用tail()可能是最簡單的,但我認為你的混淆與子集()和索引的工作方式有關。 在您的示例中,請注意您如何索引矩陣和data.frames

d[(n:n - 1), ]

是不一樣的

d[n:(n-1), ]

因此,請仔細檢查差異,因為操作順序非常重要。 subset()函數還基於邏輯指示符進行索引並具有表單

 subset(object, subset = logicalvector)

其中邏輯向量給出了要提取的行。 有關詳細信息,請參閱?subset。

這對我有用......

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

我會用: tail(d, 2)d[(n-1):n, ]希望它有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM