Vons
Vons

Reputation: 3325

Change dimension of matrix

I have a 4x10 table that I want to convert into 40x1 matrix. I am wondering why I am getting the error message when I try to change the dimensions? It was working on another table, so I think it may have something to do with the NaN in this particular table, but I'm not sure.

B="
0.2000000 0.2200000 0.2100000 0.9000000 0.2200000 0.0500000 0.2300000 0.0500000 0.1900000 0.2200000 0.3333333 0.3857143 0.4121212 0.2033898 0.3779528 0.3333333 0.4260355 0.1038961 0.1666667 0.4522613

0.1700000 0.0500000 0.1700000 0.1600000 0.1800000 0.2000000 0.2000000 0.1900000 0.0500000 0.2300000 0.4372093 0.2443890 0.4000000 0.4100719 0.4575646 0.3225806 0.3843137 0.4195804 0.1986755 0.3934426

0.0500000 0.0500000 0.0500000 0.3100000 0.0500000 0.0500000 0.0500000 0.0500000 0.3900000 0.3800000 0.5714286 0.1818182 0.5263158 0.5000000 0.1111111       NaN 0.4000000 0.1818182 0.6250000 0.2105263

0.0500000 0.0500000 0.0500000 0.0500000 0.2400000 0.0500000 0.0500000 0.1700000 0.0500000 0.0500000 0.4347826 0.2222222 0.0000000 0.0000000 0.2105263 0.2000000 0.2500000 0.6451613 0.1200000 0.1208054"
Y=read.table(text=B)
F1nn=Y[,11:20]
dim(F1nn)=c(40, 1)
> dim(F1nn)=c(40, 1)
Error in dim(F1nn) = c(40, 1) : 
  dims [product 40] do not match the length of object [10]

Upvotes: 1

Views: 43

Answers (1)

akrun
akrun

Reputation: 887231

If we need to construct a matrix, unlist the data.frame and then simply wrap with matrix

out <-  matrix(unlist(F1nn))
dim(out)
#[1] 40  1

Or if we want to use dim<-

`dim<-`(unlist(F1nn), c(40, 1))

or convert to matrix (as a matrix is a vector with dim attributes)

`dim<-`(as.matrix(F1nn), c(40, 1))

Or if it needs to be data.frame

out <- data.frame(col1 = unlist(F1nn))

Upvotes: 3

Related Questions