R:保留1行/列矩阵

时间:2018-06-18 01:14:50

标签: r matrix subset

给定一个包含一行,一列或一个单元格的矩阵,我需要在保持矩阵结构的同时重新排序行。我尝试添加drop=F,但它不起作用!我做了什么?

test = matrix(letters[1:5]) # is a matrix
test[5:1,,drop=F]           # not a matrix

test2 = matrix(letters[1:5],nrow=1) # is a matrix
test2[1:1,,drop=F]                  # not a matrix

test3 = matrix(1)  # is a matrix
test3[1:1,,drop=F] # not a matrix

3 个答案:

答案 0 :(得分:6)

我猜它是被覆盖的F; F可以设置为变量,在这种情况下它不再是假的。始终完全写出FALSE,不能将其设置为变量。

请参阅Is there anything wrong with using T & F instead of TRUE & FALSE?

同样,R Inferno,第8.1.32节,是一个很好的参考。

> F <- 1
> test = matrix(letters[1:5]) # is a matrix
> test[5:1,,drop=F]           # not a matrix
[1] "e" "d" "c" "b" "a"
> test[5:1,,drop=FALSE]       # but this is a matrix
     [,1]
[1,] "e" 
[2,] "d" 
[3,] "c" 
[4,] "b" 
[5,] "a" 
> rm(F)
> test[5:1,,drop=F]           # now a matrix again
     [,1]
[1,] "e" 
[2,] "d" 
[3,] "c" 
[4,] "b" 
[5,] "a" 

答案 1 :(得分:2)

您的问题中的代码在新的R会话中正常工作:

test = matrix(letters[1:5]) # is a matrix
result = test[5:1,,drop=F]  
result
#      [,1]
# [1,] "e" 
# [2,] "d" 
# [3,] "c" 
# [4,] "b" 
# [5,] "a" 
class(result)  # still a matrix
# [1] "matrix"
dim(result)
# [1] 5 1

即使在1x1矩阵上:

test3 = matrix(1)  # is a matrix
result3 = test3[1:1,,drop=F]
class(result3)
# [1] "matrix"
dim(result3)
# [1] 1 1

也许您已经加载了覆盖默认行为的其他软件包?是什么让你认为你不会以矩阵结束?

答案 2 :(得分:0)

以下作品:

test <- matrix(test[5:1,, drop = F], nrow = 5, ncol = 1)

使用is.matrix进行测试时,输出为矩阵。同时,您指定行数(nrow)和列数(ncol)以将其强制为您需要的行数和列数。