r - 选择单行矩阵作为矩阵

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

最佳答案

刚设置drop=FALSE如:

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

关于r - 选择单行矩阵作为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19011843/

相关文章:

r - 用标签提取 Igraph 中的所有三角形

r - 倾斜表面辐射的 solarR 时间戳

r - 根据R中的一列合并100个文件

matrix - 3D 相对于绝对变换

java - 将多维数组保存到文本文件中添加额外的列

python - 在 Python 中进行大型矩阵计算的最佳模块?

sql - DBI/ Spark : how to store the result in a Spark Dataframe?

r - 无法分配 geom_raster 大小向量的问题

matlab - 区分从不同节点开始的路径

python - 避免在 Python 中嵌套 for 循环