Letin
Letin

Reputation: 1275

Converting matrix into data.frame gives "Error in unclass(x)[...] : subscript out of bounds"

I am trying to convert a matrix into dataframe, but I get an error:

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

This is my matrix:

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

And this is how I am trying to convert it into a dataframe:

> 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

Basically, I just want a dataframe with same rows and columns just the way I have it in matrix.

Any help appreciated. Thank you.

Upvotes: 2

Views: 219

Answers (1)

jay.sf
jay.sf

Reputation: 72994

Your matrix is of class "noquote".

class(m)
# [1] "noquote"

Use unclass before coercing to "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

Data

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

Upvotes: 2

Related Questions