7

I have some data like below:

x.row10 <- setNames(data.frame(letters[1:3],1:3,2:4,3:5,4:6,5:7,6:8,7:9),
                    c("names",2004:2009,2012))
#  names 2004 2005 2006 2007 2008 2009 2012
#1     a    1    2    3    4    5    6    7
#2     b    2    3    4    5    6    7    8
#3     c    3    4    5    6    7    8    9

Now I can make them long with gather() from the tidyr package by writing:

x.row10  %>% gather(Year, Val, -names)

But when I use

x.row10  %>% gather(Year, Val, c(2004:2009,2012))

which is my intuitive choice, I get the error message

Error: Position must be between 0 and n

How come and how can this be resolved?

thelatemail
  • 91,185
  • 12
  • 128
  • 188
uncool
  • 2,613
  • 7
  • 26
  • 55
  • 5
    Add backticks as in ```df %>% gather(Year, Val, c(`2004`:`2009`,`2012`))``` or use valid columns names. `gather` thinks you are trying to select column indices which are out of range. – David Arenburg Sep 10 '15 at 22:26
  • I get an error message: Error: All select() inputs must resolve to integer column positions. The following do not: * c("2004":"2009", "2012") when using backticks – uncool Sep 10 '15 at 22:34
  • 2
    It works for me. `df` should be `x.row10` ofcourse – David Arenburg Sep 10 '15 at 22:35
  • This is a good question at it's core. I've made some adjustments to make it minimal and reproducible though. This can really help in getting quick answers in the future. – thelatemail Sep 10 '15 at 23:14

2 Answers2

6

The question is marked as solved, but I think it may be useful to post my answer. The way David Arenburg does is right. You need exact backticks for it to work. If you use the quotation marks as @uncool in the comments did, you get the same error like him:

Error: All select() inputs must resolve to integer column positions.
The following do not:
*  c("2004":"2009", "2012")

For the German keyboard users: If you don't know how to type backtick (like me a few minutes ago):

"Shift + the key on the right side of ß" and, after that, "spacebar".

Alp Aribal
  • 370
  • 1
  • 11
z4.
  • 155
  • 3
  • 10
3
x.row10  %>% gather(Year, Val, c(2:8))
HubertL
  • 19,246
  • 3
  • 32
  • 51