Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 选择一行矩阵作为矩阵_R_Matrix - Fatal编程技术网

R 选择一行矩阵作为矩阵

R 选择一行矩阵作为矩阵,r,matrix,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

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

# 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,]
一样短的命令来做同样的事情。

只需将
drop=FALSE设置为:

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

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

你不是唯一被窃听的人。数据分析软件的一个gem:“默认值是,而且一直都是,drop=TRUE;很久以前我们可能做出了一个不明智的决定,但现在是不太可能改变的向后兼容性负担之一。”