2013-09-25 133 views
3

这一直在窃听我永远。考虑以下几点:选择一行矩阵作为矩阵

# 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,]一样短的命令来完成同样的任务。

+0

你不是唯一一个窃听。来自Software for Data Analysis的一个宝石:“默认情况是,并且一直是drop = TRUE;很可能是我们很早以前的一个不明智的决定,但现在是那些不太可能改变的向后兼容负担之一。” – Peyton

回答

4

只需设置drop=FALSE为:

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

如何

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

晚20秒;) –