【问题标题】:Converting matrix into data.frame gives "Error in unclass(x)[...] : subscript out of bounds"将矩阵转换为 data.frame 给出“unclass(x)[...] 中的错误:下标越界”
【发布时间】:2019-06-19 08:31:33
【问题描述】:

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

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

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

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

【问题讨论】:

  • 很奇怪,请添加dput(t_tests_matrix[1:4,1:4]) 的输出作为对您问题的编辑
  • 嗨,杰,感谢您的来信。我现在已经提供了输出。
  • as.data.frame(unclass(t_tests_matrix[1:4,1:4]))?

标签: r dataframe matrix


【解决方案1】:

您的矩阵属于 "noquote" 类。

class(m)
# [1] "noquote"

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

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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多