Timothy Alston Timothy Alston - 10 days ago 6
R Question

How to prevent reshape() from changing variable names

I'm having some problems with the

reshape()
function. Once I have reshaped, it is changing all my variable names to be "value.var 1" for example.

The code I am using to reshape is:

test<- reshape(cdc_city, idvar= "site", timevar="variable",
direction="wide", new.row.names=FALSE)


I am guessing I am using the "new.row.names=FALSE" part wrong. I have attempted substituting FALSE for NULL, but that also didn`t work.

My aim is to transform a data set as follows:

site variable value
site 1 var 1 4
site 1 var 2 7
site 1 var 3 2
site 1 var 4 6
site 1 var 5 3
site 2 var 1 89
site 2 var 2 43
site 2 var 3 12
site 2 var 4 54
site 2 var 5 23
site 3 var 1 76
site 3 var 2 62
site 3 var 3 13
site 3 var 4 43
site 3 var 5 23


into a data set like this:

site var 1 var 2 var 3 var 4 var 5
1 4 7 2 6 3
2 89 43 12 54 23
3 76 62 13 43 23


If anyone knows how to get rid of the "value." appearing at the beginning of my variable names, that would be great! Or if there is a better bit of code I could use I am very open to that also.

Thanks,

Timothy

Answer

I suggest you use the reshape2 package instead - it's much easier to use melt and dcast than the built-in reshape():

library(reshape2)
dcast(cdc_city, site~variable, mean)
    site var 1 var 2 var 3 var 4 var 5
1 site 1     4     7     2     6     3
2 site 2    89    43    12    54    23
3 site 3    76    62    13    43    23