熔化数据帧时负箱出错

数据挖掘 r
2021-09-27 06:24:21

我有一个这样的数据框“d”:

   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

当我尝试使用“breaks”作为 id 变量来融化时,它给了我以下错误:

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

我该如何解决这个问题?我必须使用 x 轴上的中断和 y 轴上的计数来绘制 ggplot。

2个回答

对不起,这是您想要获得的那种 ggplot 吗?

在此处输入图像描述

如果是,这是它背后的代码:

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"))

不能解决您的确切问题,但另一种解决方案是尝试library(tidyr)

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

它会给你列 2:3 作为行。