1

一些问题,R 语言可能有优雅的解决方案......

给定一个包含二进制值 1 和 0 的矩阵 m,以及列索引的向量 v

  1. 我将如何编写一个函数来提取 m 中由 v 中的整数索引的每个列中值为 1 的所有行?
  2. 作为一项额外功能,如何将行索引与相应的行一起返回?

如果我举例说明,可能最好....

假设我要求的逻辑位于函数 selectByIndi​​ces(matrix, indexVector) 中。

所以如果我们有矩阵(或者可能是等效的数据框):

 >(m= matrix(c( 1, 0, 1, 1, 1,0, 1, 1, 0, 1,1, 0, 1, 1, 0,1, 1, 1, 
   0, 1,0, 1, 0, 0, 1), 5))

         [,1] [,2] [,3] [,4] [,5]
  [1,]    1    0    1    1    0
  [2,]    0    1    0    1    1
  [3,]    1    1    1    1    0
  [4,]    1    0    1    0    0
  [5,]    1    1    0    1    1

和索引向量:

 >c1 = c(1,3,4)
 >c2 =  c(4,5)
 >c3 =  c(1,3,5)

该函数的行为如下:

 >selectByIndices( m, c1)

        [,1] [,2] [,3] [,4] [,5]
  [1,]    1    0    1    1    0
  [3,]    1    1    1    1    0


 >selectByIndices( m, c2)

        [,1] [,2] [,3] [,4] [,5]
  [2,]    0    1    0    1    1
  [5,]    1    1    0    1    1


 >selectByIndices( m, c3)

    #no rows (i.e. empty collection) returned

希望它足够清楚,在此先感谢您的帮助。

4

2 回答 2

2
## Create a function that extracts the qualifying rows
f <- function(m, j) {
    m[rowSums(m[, j]) == length(j),]
    # m[apply(m[, j], 1, function(X) all(X==1)),] ## This would also work
    # which(rowSums(m[, j]) == length(j))         ## & this would get row indices
}

## Try it out
f(m, c1)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    1    1    0
# [2,]    1    1    1    1    0

f(m, c2)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    0    1    1
# [2,]    1    1    0    1    1
于 2013-01-13T04:58:51.517 回答
0
> selectRows <- function(mat, rown) suppressWarnings(mat[apply( mat[, rown], 1, all) , ])
> selectRows(m, c1)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    1    1    0
[2,]    1    1    1    1    0

>  whichRows <-function(mat, rown) suppressWarnings( which( apply( mat[, rown], 1, all) ) )
> whichRows(m, c1)
[1] 1 3
于 2013-01-13T06:52:28.747 回答