用矩阵中的列表替换奇异值

时间:2012-05-29 00:05:28

标签: r matrix replace

给定矩阵

test <- structure(list(X1 = c(3L, 0L, 3L, 1L, 2L, 2L, 1L, 2L, 2L, 3L), 
X2 = c(2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), X3 = c(0L, 
0L, 3L, 0L, 2L, 2L, 3L, 0L, 0L, 2L), X4 = c(1L, 1L, 1L, 0L, 
3L, 1L, 3L, 1L, 1L, 1L), X5 = c(3L, 3L, 1L, 3L, 1L, 3L, 2L, 
3L, 3L, 3L), X6 = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), X7 = c(2L, 2L, 2L, 3L, 2L, 2L, 3L, 2L, 2L, 2L), X8 = c(3L, 
0L, 1L, 0L, 1L, 1L, 3L, 0L, 0L, 1L), X9 = c(3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L)), .Names = c("X1", "X2", "X3", "X4", 
"X5", "X6", "X7", "X8", "X9"), row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10"), class = "data.frame")

我试图用数字序列c(0,0,1)替换“1”的每个实例,用c(0,1,0)替换3乘以(1,0,1), 0到(0,0,0)。矩阵中的每个值应该由三个二进制值的这些序列之一替换。结果矩阵的nrow应为nrow(test)* 3.显然我尝试使用索引test[test == 1] <- c(0,0,1),但这会返回错误rhs is the wrong length for indexing by a logical matrix。替换功能似乎也不起作用,返回相同的错误消息。有什么想法吗?

4 个答案:

答案 0 :(得分:5)

由于结果的维度不同(三维数组而不是二维矩阵),您不能只是逐个替换元素。

您可以使用apply:if经常用于将函数应用于矩阵的每个列或行,但我们也可以使用它将函数应用于每个元素。

apply( 
  test, 
  1:2, 
  function(u) list(c(0,0,0), c(0,0,1), c(0,1,0), c(1,0,1))[[u+1]] 
)

答案 1 :(得分:2)

你可以这样做:

Z <- matrix(c(0, 1, 0, 0,
              0, 0, 1, 0,
              0, 0, 0, 1), nrow = 3)

sapply(test, function(i)Z[,i+1])
#      X1 X2 X3 X4 X5 X6 X7 X8 X9
# [1,]  0  1  0  0  0  0  1  0  0
# [2,]  0  0  1  0  0  0  0  0  0
# [3,]  1  0  0  0  1  1  0  1  1
# ...
# [28,]  0  1  1  0  0  0  1  0  0
# [29,]  0  0  0  0  0  0  0  0  0
# [30,]  1  0  0  0  1  1  0  0  1

答案 2 :(得分:2)

您可以使用开关扩展:

matrix( sapply( c(1+data.matrix(test)), 
                    switch, c(0,0,0), c(0,0,1), c(0,1,0), c(1,0,1)) , 
        nrow=nrow(test)*3 ) 
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    1    0    0    0    1    1    0    1    1
 [2,]    0    1    0    0    0    0    1    0    0
 [3,]    1    0    0    1    1    1    0    1    1
 [4,]    0    0    0    0    1    1    0    0    1
 [5,]    0    0    0    0    0    0    1    0    0
 [6,]    0    1    0    1    1    1    0    0    1
 snipped remaining rows


str( matrix( sapply( c(1+data.matrix(test)), 
                    switch, c(0,0,0), c(0,0,1), c(0,1,0), c(1,0,1)) , 
        nrow=nrow(test)*3 ) )
  num [1:30, 1:9] 1 0 1 0 0 0 1 0 1 0 ...

答案 3 :(得分:0)

您的输入是一个数据框,因此双重申请方法也将起作用:

f <- function(u) list(c(0,0,0), c(0,0,1), c(0,1,0), c(1,0,1))[[u+1]] 
#  borrowed from Vincent Zoonekynd's answer
sapply(test, sapply, f)

请注意,输出结果完全符合OP中的要求(“结果矩阵的行数应为nrow(test)* 3”)-可能优于或不优于三维数组(结果为{ {1}}),具体取决于您要实现的目标。