我想将 Bioconductor 中的 GenomicRanges::GRanges
对象存储为基础 R data.frame
中的单个列。我想将它放在基本 R data.frame 中的原因是因为我想编写一些专门与底层 data.frames 一起使用的 ggplot2 函数。然而,我所做的任何尝试似乎都没有成果。基本上这就是我想做的:
library(GenomicRanges)
x <- GRanges(c("chr1:100-200", "chr1:200-300"))
df <- data.frame(x = x, y = 1:2)
但是该列会自动扩展,而我喜欢将其保留为单列中的有效 GRanges
对象:
> df
x.seqnames x.start x.end x.width x.strand y
1 chr1 100 200 101 * 1
2 chr1 200 300 101 * 2
当我使用 S4Vectors::DataFrame
时,它会按我想要的方式工作,除了我希望基础 R data.frame 执行相同的操作:
> S4Vectors::DataFrame(x = x, y = 1:2)
DataFrame with 2 rows and 2 columns
x y
<GRanges> <integer>
1 chr1:100-200 1
2 chr1:200-300 2
我还尝试了以下方法但没有成功:
> df <- data.frame(y = 1:2)
> df[["x"]] <- x
> df
y x
1 1 <S4 class ‘GRanges’ [package “GenomicRanges”] with 7 slots>
2 2 <NA>
Warning message: In format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x, : corrupt data frame: columns will be truncated or padded with NAs
df[["x"]] <- I(x)
Error in rep(value, length.out = nrows) : attempt to replicate an object of type 'S4'
我使用 vctrs::new_rcrd
实现 GRanges 类的 S3 变体取得了一些小成功,但这似乎是获取代表基因组范围的单列的一种非常迂回的方法。
最佳答案
我发现了一种非常简单的方法将GR对象转换为dataframe,以便您可以非常轻松地对data.frame进行操作。 annoGR2DF Repitools包中的函数可以做到这一点。
> library(GenomicRanges)
> library(Repitools)
>
> x <- GRanges(c("chr1:100-200", "chr1:200-300"))
>
> df <- annoGR2DF(x)
> df
chr start end width
1 chr1 100 200 101
2 chr1 200 300 101
> class(df)
[1] "data.frame"
关于r - GRanges 作为 base::data.frame 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59370461/