【发布时间】:2012-05-02 09:12:35
【问题描述】:
我在 R 中有一个 n x 3 矩阵,想要删除最后一列小于 x 的所有行。最好的方法是什么?
【问题讨论】:
标签: r
我在 R 中有一个 n x 3 矩阵,想要删除最后一列小于 x 的所有行。最好的方法是什么?
【问题讨论】:
标签: r
您也可以使用subset() 函数。
a <- matrix(1:9, nrow=3)
threshhold <- 8
subset(a, a[ , 3] < threshhold)
【讨论】:
与@JeffAllen 方法相同,但更详细一点,并且可以推广到任何大小的矩阵。
data <- rbind(c(1,2,3), c(1, 7, 4), c(4,6,7), c(3, 3, 3), c(4, 8, 6))
data
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 7 4
[3,] 4 6 7
[4,] 3 3 3
[5,] 4 8 6
#
# set value of x
x <- 3
#
# return matrix that contains only those rows where value in
# the final column is greater than x.
# This will scale up to a matrix of any size
data[data[,ncol(data)]>x,]
[,1] [,2] [,3]
[1,] 1 7 4
[2,] 4 6 7
[3,] 4 8 6
【讨论】:
m <- matrix(rnorm(9), ncol=3)
m <- m[m[,3]>0,]
创建一个矩阵,然后重新定义该矩阵以仅包含第三列大于 0 的行 (m[,3] > 0)。
【讨论】: