5

I have a dataframe 'd' like this:

   breaks counts.x counts.y
1     -20        1        1
2     -15        0        1
3     -10        0        5
4      -5        4       18
5       0       13       27
6       5       18       25
7      10        9       12
8      15        2        1
9      20        1        7
10     25       NA        0
11     30       NA        1

When I try to melt using 'breaks' as id variable it is giving me the following error:

 d=melt(d,id=breaks)
Error in varnames[id.vars] : 
  only 0's may be mixed with negative subscripts

How can I resolve this? I have to draw a ggplot using breaks on x axis and counts on y axis.

Emre
  • 10,491
  • 1
  • 29
  • 39
pinky
  • 151
  • 1
  • 9

2 Answers2

1

I am sorry, is this the kind of ggplot you want to obtain ?

enter image description here

If yes this is the code behind it:

library(reshape)
library(ggplot2)

d <- data.frame(breaks = c(-20, -15, -10, -5,  0, 5, 10, 15, 20, 25, 30),
                counts.x  = c(1, 0, 0 ,4 , 13, 18, 9, 2, 1, NA, NA),
                counts.y = c(1, 1, 5, 18, 27, 25, 12, 1, 7 , 0, 1))

d <- melt(d, id = "breaks")

ggplot(d, aes(x = breaks, y = value)) + geom_point(aes(colour = variable)) +
       labs(title = "Bins vs. Counts", x = "Bins", y = "Counts") +
       theme(plot.title = element_text(face = "bold"))
  • YEs.. I have to make ggplot same as yours but I was getting an error while melting. – pinky Apr 01 '16 at 16:32
  • Because @pinky you had d <- melt(d, id = breaks) which can fail in two ways - first you must have an object called breaks lying around otherwise R will give object 'breaks' not found and secondly because you passed the value of breaks (ie a vector of numeric values) rather than the name of the id column as a scalar character value as the answerer here has done correctly with melt(d, id = "breaks") - the quote marks are vital. – Spacedman Apr 23 '18 at 14:55
1

Not a fix to your exact problem, but an alternative solution would be to try library(tidyr):

library(tidyr)
d <- gather(d,"variable","value",2:3)

And it will give you columns 2:3 as rows.

TBSRounder
  • 883
  • 6
  • 12