0

I tried to reshape the data frame that converting the entries in one column to be the row names. Then I use cast () , but I gotta following error when I retrieved the data inside new data frame.

Here is original data frame:

ID Type rating
1  1    3.5
1  2    4.0
2  2    2.5

And the code:

r_mat <-cast(r_data,ID~type)    
r_mat$1
unexpected numeric constant in r_mat$1

here is new data frame looks like:

ID  1    2 
1  3.5  4.0
2  NA   2.5

Can anyone kindly help me coping with the error ? Thanks!

Enze Mao
  • 1
  • 1
  • 1
    Try `r_mat$"1"`. The problem is that numbers are invalid column names in data.frames and `cast()` does not seem to warn you or convert them for you. – MrFlick Mar 08 '15 at 17:33
  • @MrFlick, thanks, it does work ! but is there any way to convert the names to valid ones? except using `col.names()` as I need to keep the the column names as numbers and actually, I have about 1000 columns in the similar way, i.e the column names is from 1 to 1000. – Enze Mao Mar 08 '15 at 18:01

1 Answers1

2

You can use make.names in {base} to "Make syntactically valid names out of character vectors" as follows:

colnames(r_mat) <-
  make.names(colnames(r_mat),unique=T)

For a set of columns with numeric names, this will insert an "X" character in front of each number, e.g. X1,X2...

For details on the function specification, see: https://stat.ethz.ch/R-manual/R-devel/library/base/html/make.names.html

childerino
  • 331
  • 2
  • 5