5

I'm trying to use gather in the tidyr package, but I'm not able to change the outputted column names from the default names. For instance:

df = data.frame(time = 1:100,a = 1:100,b = 101:200)
df.long = df %>% gather("foo","bar",a:b)
colnames(df.long)

gives me

[1] "time"     "variable" "value"   

but shouldn't it be "time" "foo" "bar" ?

I can change "foo" and "bar" to anything I want, and it still gives me "variable" and "value" as my column names.

Help. What am I missing here?

dvdkamp
  • 156
  • 5
  • Your code worked for me. I had `dplyr` loaded as well. – John Paul Sep 30 '14 at 22:29
  • 3
    Hey all, My problem was that I had plyr and dplyr loaded at the same time. All I needed to do, is write `detach("package:plyr")` and the code worked – dvdkamp Sep 30 '14 at 22:35
  • @dvdkamp: This sometimes may not work especially when dplyr could be loaded via namespace. – KFB Oct 04 '14 at 02:14

1 Answers1

2

This could possibly be a bug. If you are willing to try else, like melt() of data.table, you could do below:

# Need to load both data.table and reshape2
# For more information, could check ?data.table
library(reshape2); library(data.table)
setDT(df)
df %>% melt(id.vars = "time", variable.name = "foo", value.name = "bar")

> First 20 rows
    time foo bar
1:    1   a   1
2:    2   a   2
3:    3   a   3
4:    4   a   4
5:    5   a   5
6:    6   a   6
7:    7   a   7
8:    8   a   8
9:    9   a   9
10:   10   a  10
11:    1   b  11
12:    2   b  12
13:    3   b  13
14:    4   b  14
15:    5   b  15
16:    6   b  16
17:    7   b  17
18:    8   b  18
19:    9   b  19
20:   10   b  20
KFB
  • 3,501
  • 3
  • 15
  • 18