-
-
Save klmr/4898c3eb1a5216850134 to your computer and use it in GitHub Desktop.
Example of a non-trivial function to apply over all columns of a table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
complete_table = function (data, labels) { | |
tbl = table(data) | |
label_pos = match(labels, names(tbl)) | |
tbl = tbl[label_pos] | |
names(tbl) = labels | |
tbl[is.na(tbl)] = 0 | |
`class<-`(tbl, 'table') | |
} | |
# GC = (C + G) / (A + C + G + T) | |
gc = function (gene) { | |
codon_components = lapply(strsplit(names(gene), ''), | |
complete_table, labels = c('A', 'C', 'G', 'T')) | |
codon_components = Map(`*`, codon_components, gene) | |
base_freqs = Reduce(`+`, codon_components) | |
with(as.list(base_freqs), (C + G) / (A + C + G + T)) | |
} | |
# Usage: | |
gc(c(AAA = 4, AAC = 2, AAG = 0, AAT = 0, ACA = 3, …, TTT = 6)) | |
# Or, in the case of my actual table: | |
genes = transform(genes, GC = apply(genes, 1, gc)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment