优雅的索引,直到向量/矩阵的结尾


74

在R中是否可以说-我想要从位置i到向量/矩阵结尾的所有索引?假设我要从第3列开始添加子矩阵。我目前只知道这种方式:

A = matrix(rep(1:8, each = 5), nrow = 5) # just generate some example matrix...

A[,3:ncol(A)] # get submatrix from 3rd column onwards

但是我真的需要写ncol(A)吗?从“第三栏起”说出来没有优雅的方法吗?像A[,3:]什么?(或A[,3:...])?

Answers:


102

有时,告诉R不需要的内容会更容易。换句话说,使用负索引从矩阵中排除列:

这是两种产生相同结果的替代方法:

A[, -(1:2)]
A[, -seq_len(2)]

结果:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    3    4    5    6    7    8
[3,]    3    4    5    6    7    8
[4,]    3    4    5    6    7    8
[5,]    3    4    5    6    7    8

但要回答您的问题:ncol用于查找列数。(类似地nrow,找到行数。)

A[, 3:ncol(A)]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    3    4    5    6    7    8
[3,]    3    4    5    6    7    8
[4,]    3    4    5    6    7    8
[5,]    3    4    5    6    7    8

17

对于行(不按你的例子列),然后head()tail()可以利用。

A <- matrix(rep(1:8, each = 5), nrow = 5)
tail(A, 3)

几乎与

A[3:dim(A)[1],]

(所有打印的行名/索引都不同)。

这些也适用于向量和数据帧:

> tail(1:10, 4)
[1]  7  8  9 10
> tail(data.frame(A = 1:5, B = 1:5), 3)
  A B
3 3 3
4 4 4
5 5 5

对于列版本,您可以进行调整tail(),但这有点棘手。我不知道是否NROW()NCOL()这里可能是有用的,而不是dim()

> A[, 3:NCOL(A)]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    3    4    5    6    7    8
[3,]    3    4    5    6    7    8
[4,]    3    4    5    6    7    8
[5,]    3    4    5    6    7    8

或翻转它的头部,而不是问R东西,而是问它放东西。这是封装此功能的函数:

give <- function(x, i, dimen = 1L) {
    ind <- seq_len(i-1)
    if(isTRUE(all.equal(dimen, 1L))) { ## rows
        out <- x[-ind, ]
    } else if(isTRUE(all.equal(dimen, 2L))) { ## cols
        out <- x[, -ind]
    } else {
        stop("Only for 2d objects")
    }
    out
}

> give(A, 3)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    2    3    4    5    6    7    8
[2,]    1    2    3    4    5    6    7    8
[3,]    1    2    3    4    5    6    7    8
> give(A, 3, dimen = 2)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    4    5    6    7    8
[2,]    3    4    5    6    7    8
[3,]    3    4    5    6    7    8
[4,]    3    4    5    6    7    8
[5,]    3    4    5    6    7    8

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.