首页 > 解决方案 > 如何在不更改行数和列数的情况下从矩阵创建数据框?

问题描述

我创建了一个表格,它结合了数字(相关性)和重要性(星号)。我想将我的数据转换为数据框以进行进一步处理。我尝试了 tibble 和 as.data.frame,但都将我的矩阵变成了 1xn 帧。我显然做错了什么。但是什么?

R <- matrix(data=-3:2/10, ncol=3, nrow=2, byrow=TRUE)
mystars <- matrix(data=c("*  ", "*  ", "*  ", "***", "   ", "** "), ncol=3, nrow=2, byrow=TRUE)
R1 <- tibble(paste(R, mystars))
R2 <- as.data.frame(paste(R, mystars), stringsAsFactors = FALSE, ncol=3, nrow=2, byrow=TRUE)

这给出了一个 6x1 tibble 和一个 6x1 数据帧,而不是原始的 2x3 矩阵。

标签: rdataframematrixtibble

解决方案


您可以使用[]来保留原始矩阵的尺寸。

R[] <- trimws(paste(R, mystars))

#       [,1]     [,2]     [,3]    
#[1,] "-0.3 *" "-0.2 *" "-0.1 *"
#[2,] "0 ***"  "0.1"    "0.2 **"

推荐阅读