R reshape () function changes column labels

I want to convert my data from long to wide format. If finding really annoying that reshapechanges column labels, is there a way to avoid this?

For example, if I had data in a long format, for example:

Year Name Value
1996 a    1
1997 a    2
1998 b    3
1999 b    4

I would use reshape()like this

reshape(long, timevar = "Year", idvar = "Name", direction = "wide")

The conversion itself works fine, but the column names will look like this:

Name Time.1996 Time.1997 Time.1998 Time.1999 

The only thing I can think of now is to rename the column names manually, which is very annoying if you need to do this for multiple datasets.

+5
source share
1 answer

I don’t see the question here, but if it bothers you much, there are several alternatives.

R xtabs ( ) .

as.data.frame.matrix(xtabs(Value ~ Name + Year, long))
#   1996 1997 1998 1999
# a    1    2    0    0
# b    0    0    3    4

, , dcast "reshape2".

library(reshape2)
dcast(long, Name ~ Year)
# Using Value as value column: use value.var to override.
#   Name 1996 1997 1998 1999
# 1    a    1    2   NA   NA
# 2    b   NA   NA    3    4

, , , . reshape, , . , "" , :

> long$Something <- 5:8
> reshape(long, timevar = "Year", idvar = "Name", direction = "wide")
  Name Value.1996 Something.1996 Value.1997 Something.1997 Value.1998
1    a          1              5          2              6         NA
3    b         NA             NA         NA             NA          3
  Something.1998 Value.1999 Something.1999
1             NA         NA             NA
3              7          4              8

, , , 1996 "", "-".


, reshape ( ), ( , "" ), :

setNames. , : , .

> setNames(reshape(long, timevar = "Year", idvar = "Name", direction = "wide"), 
+          c("Name", long$Year))
  Name 1996 1997 1998 1999
1    a    1    2   NA   NA
3    b   NA   NA    3    4

sub gsub, . , , , , , .

> wide <- reshape(long, timevar = "Year", idvar = "Name", direction = "wide")
> names(wide)
[1] "Name"       "Value.1996" "Value.1997" "Value.1998" "Value.1999"
> names(wide) <- gsub("Value.", "", names(wide))
> wide
  Name 1996 1997 1998 1999
1    a    1    2   NA   NA
3    b   NA   NA    3    4
+13

All Articles