将矩阵转换为data.frame会显示“ unclass(x)[...]中的错误:下标超出范围”

时间:2019-06-19 08:31:33

标签: r dataframe matrix

我正在尝试将矩阵转换为数据帧,但出现错误:

Error in unclass(x)[...] : subscript out of bounds

这是我的矩阵:

> t_tests_matrix [1:4,1:4]
                   t       df        p-value    CI-lower          
[1,]   Age         -18.77  1737.38   1.173e-58  -5.62
[2,]   Sex         30.86   1774.26   0.0001     0.035
[3,]   BMI         -15.42  2399.27   2.13e-51   -2.48 
[4,]   Smoking     -4.44   1815.79   9.14e-06   -0.22

> ncol(t_tests_matrix)
[1] 11

> nrow(t_tests_matrix)
[1] 282

> dput(t_tests_matrix[1:4,1:4])
structure(c("-16.775788723263", "3.86574432077067", "-15.4206993261167", 
"-4.44908941830164", "1737.3858539591", "1774.26050619806", "2399.27865240686", 
"1815.79209956541", "1.17398448843737e-58", "0.000114741095154172", 
"3.1393399581141e-51", "9.14651655854383e-06", "-5.62124733617094", 
"0.0350847324324739", "-2.48981315277103", "-0.223776515933009"
), .Dim = c(4L, 4L), .Dimnames = list(c("Age", "Sex", "BMI", 
"Smoking"), c("t", "df", "p-value", "CI-lower")), class = "noquote")

这就是我试图将其转换为数据帧的方式:

> t_tests_df <- as.data.frame(t_tests_matrix)

> t_tests_df
Error in unclass(x)[...] : subscript out of bounds

> t_tests_df [1:4,1:4]
Error in `[.data.frame`(t_tests_results, 1:4, 1:4) : 
  undefined columns selected

基本上,我只想要一个数据行和列相同的数据框,就像在矩阵中一样。

任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:2)

您的矩阵属于"noquote"类。

class(m)
# [1] "noquote"

在强制使用unclass之前使用"data.frame"

as.data.frame(unclass(m))
#                         t               df              p-value           CI-lower
# Age      -16.775788723263  1737.3858539591 1.17398448843737e-58  -5.62124733617094
# Sex      3.86574432077067 1774.26050619806 0.000114741095154172 0.0350847324324739
# BMI     -15.4206993261167 2399.27865240686  3.1393399581141e-51  -2.48981315277103
# Smoking -4.44908941830164 1815.79209956541 9.14651655854383e-06 -0.223776515933009

数据

m <- structure(c("-16.775788723263", "3.86574432077067", "-15.4206993261167", 
"-4.44908941830164", "1737.3858539591", "1774.26050619806", "2399.27865240686", 
"1815.79209956541", "1.17398448843737e-58", "0.000114741095154172", 
"3.1393399581141e-51", "9.14651655854383e-06", "-5.62124733617094", 
"0.0350847324324739", "-2.48981315277103", "-0.223776515933009"
), .Dim = c(4L, 4L), .Dimnames = list(c("Age", "Sex", "BMI", 
"Smoking"), c("t", "df", "p-value", "CI-lower")), class = "noquote")