我想将Bioconductor的GenomicRanges::GRanges
对象作为单列存储在基本R data.frame
中。我之所以希望将其包含在基本R data.frame中,是因为我想编写一些ggplot2函数,这些函数只能在后台使用data.frame。但是,我所做的任何尝试似乎都没有取得成果。基本上这就是我想做的:
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>
警告消息:在format.data.frame(如果(省略)x [seq_len(n0),,drop = FALSE]否则x,:数据框损坏:列将被截断或用NA填充
df[["x"]] <- I(x)
rep(value,length.out = nrows)错误:尝试复制类型为“ S4”的对象]
[使用vctrs::new_rcrd
实现GRanges类的S3变体有些成功,但这似乎是获得代表基因组范围的单列的一种非常column回的方法。
一种不实用但实用的解决方案是使用GenomicRanges的访问器函数,然后转换为相关的数据向量,即数字或字符。我添加了magrittr,但也可以不使用它。
library(GenomicRanges)
library(magrittr)
x <- GRanges(c("chr1:100-200", "chr1:200-300"))
df <- data.frame(y = 1:2)
df$chr <- seqnames(x) %>% as.character
df$start <- start(x) %>% as.numeric
df$end <- end(x) %>% as.numeric
df$strand <- strand(x) %>% as.character
df$width <- width(x) %>% as.numeric
df