Nazer
Nazer

Reputation: 3774

Remove indexing from matrix in R

I am trying to make a barplot for which I need my data in a matrix. I have made some really nice plots before when my matrix looked like this:

       0%   20%   40%   60%  80%
C2   0.22  0.94  1.66  2.38 3.10
CC  -1.38 -0.66  0.06  0.79 1.51
CCW -1.61 -0.87 -0.13  0.62 1.36
P   -1.13 -0.16  0.81  1.78 2.76
PF   0.03  0.72  1.42  2.11 2.80
S2  -2.34 -1.61 -0.88 -0.16 0.57

For the rest of my data, I had to convert it from a dataframe, which I did using as.matrix(df). This matrix looks like this:

     trt   2009     2010      2011     
[1,] "C2"  "9.0525" " 8.1400" " 8.1400"
[2,] "CC"  "5.4200" " 4.7975" " 4.7975"
[3,] "CCW" "4.9675" " 4.0400" " 4.0400"
[4,] "P"   "9.3150" "10.3500" "10.3500"
[5,] "PF"  "9.0950" " 3.3375" " 3.3375"
[6,] "S2"  "3.1725" " 3.1125" " 3.1125"

It won't work with the barplot function. I think I need to remove the index column, but haven't been able to. And what is with the quotes? I though a matrix was a matrix, so I'm not sure what is going on here.

Upvotes: 1

Views: 13400

Answers (1)

Luciano Selzer
Luciano Selzer

Reputation: 10016

The quotes means your matrix is in mode character. This is because matrix, as opposed to data.frame which are superficially similar, can only hold one type. Because alphanumeric characters cannot be converted to numeric, your matrix is in mode character. I would be easier to remove the first column before converting it to matrix and save yourself of converting the matrix to numeric.

m <- as.matrix(df[, -1])

#To add the row.names.

row.names(m) <- df[, 1]

Upvotes: 2

Related Questions