选择单行矩阵作为矩阵

时间:2013-09-25 17:50:46

标签: r matrix

这一直困扰着我。请考虑以下事项:

# Part A #
# Make a silly simple matrix with column names
x = matrix(1:4, ncol = 2)
colnames(x) = c("a","b")

# Part B #
# Pick out the first row of the matrix.  This is not a matrix, 
#   and the column names are no longer accessible by colnames()
y = x[1,]
y
is.matrix(y)
colnames(y)

# Part C #
# But here is what I want:
y = matrix(x[1,], nrow = 1, dimnames = list(c(), colnames(x)))

有没有办法用更少的处理步骤或更少的代码来实现C部分?似乎应该有一个几乎与x[1,]一样短的命令来做同样的事情。

2 个答案:

答案 0 :(得分:5)

只需设置drop=FALSE,如下所示:

> y = x[1,, drop=FALSE]
> y
     a b
[1,] 1 3

答案 1 :(得分:4)

怎么样

x[1,,drop=FALSE]
     a b
[1,] 1 3