[英]Extracting subset of the data frame in R
Suppose I read a csv file into a data frame called "d". 假设我将csv文件读入名为“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.
我尝试了下面但它打印的所有内容都是从n-1开始的。 Can someone help me understand this behavior please?
有人可以帮我理解这种行为吗?
> n<-nrow(d)
> n
[1] 153
> subset(d[n:n-1,])
You can just use tail 你可以用尾巴
tail(d, 2)
Will give the last two rows. 将给出最后两行。
@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. @mnel是正确的,使用tail()可能是最简单的,但我认为你的混淆与子集()和索引的工作方式有关。 In your example be mindful of how you index matrices and data.frames since
在您的示例中,请注意您如何索引矩阵和data.frames
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()函数还基于逻辑指示符进行索引并具有表单
subset(object, subset = logicalvector)
where the logical vector gives the rows that you want to extract. 其中逻辑向量给出了要提取的行。 See ?subset for more detail.
有关详细信息,请参阅?subset。
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
我会用: tail(d, 2)
或d[(n-1):n, ]
希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.