forked from jimhester/GenomicRanges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakeGRangesFromDataFrame.R
243 lines (222 loc) · 9.25 KB
/
makeGRangesFromDataFrame.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
### =========================================================================
### makeGRangesFromDataFrame()
### -------------------------------------------------------------------------
### Must return NULL or a Seqinfo object.
.normarg_seqinfo <- function(seqinfo)
{
if (is.null(seqinfo) || is(seqinfo, "Seqinfo"))
return(seqinfo)
if (is.character(seqinfo))
return(Seqinfo(seqinfo))
if (is.numeric(seqinfo)) {
seqlevels <- names(seqinfo)
if (is.null(seqlevels))
stop("when a numeric vector, 'seqinfo' must have names")
return(Seqinfo(seqlevels, seqlengths=seqinfo))
}
stop("'seqinfo' must be NULL, or a Seqinfo object, or a character vector ",
"of seqlevels, or a named numeric vector of sequence lengths")
}
.normarg_field <- function(field, what)
{
if (!is.character(field) || any(is.na(field)))
stop("'", what, ".field' must be a character vector with no NAs")
tolower(field)
}
.collect_prefixes <- function(df_colnames, field)
{
df_colnames_nc <- nchar(df_colnames)
prefixes <- lapply(field,
function(suf) {
pref_nc <- df_colnames_nc - nchar(suf)
idx <- which(substr(df_colnames, pref_nc + 1L, df_colnames_nc) ==
suf)
substr(df_colnames[idx], 1L, pref_nc[idx])
})
unique(unlist(prefixes))
}
.find_start_end_cols <- function(df_colnames, start.field, end.field)
{
idx1 <- which(df_colnames %in% start.field)
idx2 <- which(df_colnames %in% end.field)
if (length(idx1) == 1L && length(idx2) == 1L)
return(list(c(start=idx1, end=idx2), ""))
if (length(idx1) == 0L && length(idx2) == 0L) {
prefixes1 <- .collect_prefixes(df_colnames, start.field)
prefixes2 <- .collect_prefixes(df_colnames, end.field)
if (length(prefixes1) == 1L && length(prefixes2) == 1L
&& prefixes1 == prefixes2)
{
prefix <- prefixes1
idx1 <- which(df_colnames %in% paste0(prefix, start.field))
idx2 <- which(df_colnames %in% paste0(prefix, end.field))
if (length(idx1) == 1L && length(idx2) == 1L)
return(list(c(start=idx1, end=idx2), prefix))
}
}
stop("cannnot determine start/end columns")
}
.find_width_col <- function(df_colnames, width.field, prefix)
{
idx <- which(df_colnames %in% paste0(prefix, width.field))
if (length(idx) == 0L)
idx <- which(df_colnames %in% width.field)
if (length(idx) == 0L)
return(NA_integer_)
if (length(idx) >= 2L) {
warning("cannnot determine width column unambiguously")
return(idx[[1L]])
}
idx
}
.find_seqnames_col <- function(df_colnames, seqnames.field, prefix)
{
idx <- which(df_colnames %in% paste0(prefix, seqnames.field))
if (length(idx) == 0L)
idx <- which(df_colnames %in% seqnames.field)
if (length(idx) == 0L)
stop("cannnot find seqnames column")
if (length(idx) >= 2L)
stop("cannnot determine seqnames column unambiguously")
idx
}
.find_strand_col <- function(df_colnames, strand.field, prefix)
{
idx <- which(df_colnames %in% paste0(prefix, strand.field))
if (length(idx) == 0L)
idx <- which(df_colnames %in% strand.field)
if (length(idx) == 0L)
return(NA_integer_)
if (length(idx) >= 2L)
stop("Cannnot determine strand column unambiguously. ",
"(You can use\n 'ignore.strand=FALSE' to ignore ",
"strand information.)")
idx
}
### Returns a named integer vector of length 5. Names are: seqnames, start,
### end, width, and strand. The values must be valid column numbers, except
### for the width and strand elements that can also be NAs.
.find_GRanges_cols <- function(df_colnames,
seqnames.field=c("seqnames", "seqname",
"chromosome", "chrom",
"chr", "chromosome_name"),
start.field="start",
end.field=c("end", "stop"),
strand.field="strand",
ignore.strand=FALSE)
{
## Automatic detection of seqnames/start/end/strand columns is case
## insensitive.
df_colnames0 <- tolower(df_colnames)
seqnames.field0 <- .normarg_field(seqnames.field, "seqnames")
start.field0 <- .normarg_field(start.field, "start")
end.field0 <- .normarg_field(end.field, "end")
start_end_cols <- .find_start_end_cols(df_colnames0,
start.field0,
end.field0)
prefix <- start_end_cols[[2L]]
## Name of "width" field is not under user control for now (until we need
## need that).
width_col <- .find_width_col(df_colnames0, "width", prefix)
seqnames_col <- .find_seqnames_col(df_colnames0,
seqnames.field0,
prefix)
if (ignore.strand) {
strand_col <- NA_integer_
} else {
strand.field0 <- .normarg_field(strand.field, "strand")
strand_col <- .find_strand_col(df_colnames0,
strand.field0,
prefix)
}
c(seqnames=seqnames_col, start_end_cols[[1L]], width=width_col,
strand=strand_col)
}
### 'df' must be a data.frame or DataFrame object.
makeGRangesFromDataFrame <- function(df,
keep.extra.columns=FALSE,
ignore.strand=FALSE,
seqinfo=NULL,
seqnames.field=c("seqnames", "seqname",
"chromosome", "chrom",
"chr", "chromosome_name"),
start.field="start",
end.field=c("end", "stop"),
strand.field="strand",
starts.in.df.are.0based=FALSE)
{
## Check args.
if (!(is.data.frame(df) || is(df, "DataFrame")))
df <- as.data.frame(df)
if (!isTRUEorFALSE(keep.extra.columns))
stop("'keep.extra.columns' must be TRUE or FALSE")
if (!isTRUEorFALSE(ignore.strand))
stop("'ignore.strand' must be TRUE or FALSE")
ans_seqinfo <- .normarg_seqinfo(seqinfo)
if (!isTRUEorFALSE(starts.in.df.are.0based))
stop("'starts.in.df.are.0based' must be TRUE or FALSE")
granges_cols <- .find_GRanges_cols(names(df),
seqnames.field=seqnames.field,
start.field=start.field,
end.field=end.field,
strand.field=strand.field,
ignore.strand=ignore.strand)
## Prepare 'ans_seqnames'.
ans_seqnames <- df[[granges_cols[["seqnames"]]]]
## Prepare 'ans_ranges'.
ans_start <- df[[granges_cols[["start"]]]]
ans_end <- df[[granges_cols[["end"]]]]
if (!is.numeric(ans_start) || !is.numeric(ans_end))
stop("\"", names(df)[granges_cols[["start"]]], "\" and ",
"\"", names(df)[granges_cols[["end"]]], "\" columns ",
"must be numeric")
if (starts.in.df.are.0based)
ans_start <- ans_start + 1L
ans_names <- rownames(df)
if (identical(ans_names, as.character(seq_len(nrow(df)))))
ans_names <- NULL
ans_ranges <- IRanges(ans_start, ans_end, names=ans_names)
## Prepare 'ans_strand'.
if (is.na(granges_cols[["strand"]]) || ignore.strand) {
ans_strand <- "*"
} else {
ans_strand <- df[[granges_cols[["strand"]]]]
}
## Prepare 'ans_mcols'.
if (keep.extra.columns) {
drop_idx <- c(granges_cols[["seqnames"]],
granges_cols[["start"]],
granges_cols[["end"]])
if (!is.na(granges_cols[["width"]]))
drop_idx <- c(drop_idx, granges_cols[["width"]])
if (!is.na(granges_cols[["strand"]]))
drop_idx <- c(drop_idx, granges_cols[["strand"]])
ans_mcols <- df[-drop_idx]
} else {
ans_mcols <- NULL
}
## Prepare 'ans_seqinfo'.
if (is.null(ans_seqinfo)) {
## Only if 'ans_seqnames' is a factor-Rle, we preserve the seqlevels
## in the order they are in 'levels(ans_seqnames)'. Otherwise, we
## order them according to rankSeqlevels().
seqlevels <- levels(ans_seqnames)
if (is.null(seqlevels)) {
seqlevels <- unique(ans_seqnames)
if (!is.character(seqlevels))
seqlevels <- as.character(seqlevels)
}
if (!(is(ans_seqnames, "Rle") && is.factor(runValue(ans_seqnames))))
seqlevels[rankSeqlevels(seqlevels)] <- seqlevels
ans_seqinfo <- Seqinfo(seqlevels)
}
## Make and return the GRanges object.
GRanges(ans_seqnames, ans_ranges, strand=ans_strand,
ans_mcols, seqinfo=ans_seqinfo)
}
setAs("data.frame", "GRanges",
function(from) makeGRangesFromDataFrame(from, keep.extra.columns=TRUE)
)
setAs("DataFrame", "GRanges",
function(from) makeGRangesFromDataFrame(from, keep.extra.columns=TRUE)
)