选择列R的新矩阵

时间:2013-11-12 09:59:28

标签: r matrix filter

说你有R

m = matrix(0, 10, 5, dimnames = list(
                                    c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"), 
                                    c(1, 2, 3, 4, 5)))
m[1,] = c(0,0,0,0,1)
m[2,] = c(0,0,0,1,1)
m[3,] = c(0,0,1,1,1)
m[4,] = c(0,0,1,1,0)
m[5,] = c(1,0,0,0,0)
m[6,] = c(1,1,1,0,0)
m[7,] = c(0,1,1,0,0)
m[8,] = c(0,1,1,0,0)
m[9,] = c(0,1,1,1,0)
m[10,] = c(1,1,1,0,1)

上面你看到矩阵m。我有另一个矩阵p,以便:

p = matrix(0, 1, 5, dimnames = list(
                                    c("A"), 
                                    c(1, 2, 3, 4, 5)))
p[1,] = c(0.2,0.03,0.2,0.01,1)

我有一个说明特定值(p值)的矩阵,只有一列。 我想从m创建一个新矩阵,但只有列中p的那一列的值是< 0.05

所以基本上,我想在R:

for (i in 1:length(p){
    if (p[1,i] < 0.05){
        #remember i in a list to extract later?
        mycols.append(i)
}}

myNewMat <- matrix[,mycols]

THX

1 个答案:

答案 0 :(得分:1)

请尝试以下内容,看看这是否是您想要的。

myNewMat <- m[,p < 0.05]