r - 将向量转置为单列?

标签 r

<分区>

不敢相信我以前从未在 R 中注意到这一点!

如果我转置一个向量,它不会像我期望的那样给出单列矩阵。

示例

test <- c(1, 2, 3, 4)

t(test)

[,1] [,2] [,3] [,4]
[1,] 1 2 3 4

这在我的一个功能中造成了问题。

有什么解决方法吗?

最佳答案

我们用 matrix 包装,默认情况下它给出一个列

matrix(test)
#     [,1]
#[1,]    1
#[2,]    2
#[3,]    3
#[4,]    4

正如 ?matrix 的文档所说

If one of nrow or ncol is not given, an attempt is made to infer it from the length of data and the other parameter. If neither is given, a one-column matrix is returned.


此外,matrix 是一个具有dim 属性的vector,因此,另一种选择是分配dim 属性

dim(test) <- c(length(test), 1)

transpose之所以这样做是根据?t

When x is a vector, it is treated as a column, i.e., the result is a 1-row matrix.

关于r - 将向量转置为单列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199028/

相关文章:

R:ggplot2 中的 qplot 错误:缺少参数 "env",没有默认值

r - 在没有 for 循环的情况下更改数据框中多列的类

r - 为什么基R中的Date类有一个double支持

r - 更改 jupyter notebook 警告语言

r - 根据列表对象中的条件过滤 R 中的列表

R匹配键值向量与不规则字符串向量

r - 如何在 R 中的传单上的标记上显示标签?

r - 标准化变量 data.table

r - 如何将表格添加到ggplot?

r - 使用portfolio.optim 函数在R 中进行二次编程时出错