Reshape2熔化错误“'id.vars'中的一个或多个值无效”

时间:2019-07-13 21:25:35

标签: r reshape reshape2 melt

我正在尝试融合两列,并通过执行以下操作将行名用作ID:

fst = fread("file.fst")
colnames(fst) = c("fst2", "snp", "chr", "pos", "fst")
d <- melt(fst[,c("fst","fst2")], id.vars="as.numeric(row.names(fst))")

但是我遇到了错误:

Error in melt.data.table(fst[, c("fst", "fst2")], id.vars = "as.numeric(row.names(fst))") :
  One or more values in 'id.vars' is invalid.

数据看起来像

 fst2          snp chr      pos      fst
1: 0.265838        CLIC6   1    25001 0.150339
2: 0.390470        RUNX1   1   115001 0.259316
3: 0.126332        SETD4   1   635001 0.128946
4: 0.236400 LOC100222525   1   645001 0.117627
5: 0.181189       DOPEY2   1   705001 0.190456

> class(fst)
[1] "data.table" "data.frame"
> typeof(fst)
[1] "list"
> str(fst)
Classes ‘data.table’ and 'data.frame':  10066 obs. of  5 variables:
 $ fst2: num  0.266 0.39 0.126 0.236 0.181 ...
 $ snp : chr  "CLIC6" "RUNX1" "SETD4" "LOC100222525" ...
 $ chr : int  1 1 1 1 1 1 1 1 1 1 ...
 $ pos : int  25001 115001 635001 645001 705001 735001 745001 955001 985001 1105001 ...
 $ fst : num  0.15 0.259 0.129 0.118 0.19 ...
 - attr(*, ".internal.selfref")=<externalptr>

怎么了?

1 个答案:

答案 0 :(得分:0)

我将其用作数据框

d <- melt(as.data.frame(fst[,c("fst","fst2")], id.vars="id"))

p <-ggplot(d, aes(id,value)) + geom_line(aes(colour = variable))

ggsave(filename = "fstavgcor.png", p , width = 6, height = 4, dpi = 300, units = "in", device='png')

但不确定是否正确,因为现在当我尝试绘图时会得到这个。

Error in FUN(X[[i]], ...) : object 'id' not found

这可能是解决方法:

fst = fread("bamgenes_singlepos_genes.fst")
colnames(fst) = c("fst2", "snp", "chr", "pos", "fst")
fst$id <- row.names(fst)
d <- melt(as.data.frame(fst[,c("fst","fst2","id")]))
colnames(d) = c("id", "variable", "value")

# Everything on the same plot
p<- ggplot(d, aes(as.numeric(id), value, col=variable)) + 
  geom_point() + 
  geom_line() +

  # Custom the theme:
  theme_bw() +
  theme(
    legend.position="none",
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    axis.text.y = element_text(size=10, margin = margin(t = 20, r = 20, b = 20, l = 20))
  )
ggsave(filename = "fstavgcor.png", p , width = 6, height = 4, dpi = 300, units = "in", device='png')