Skip to content

Instantly share code, notes, and snippets.

@mikelove
Created November 3, 2023 02:51
Show Gist options
  • Save mikelove/0400d2c9485b06c7691ac3a746b6853a to your computer and use it in GitHub Desktop.
Save mikelove/0400d2c9485b06c7691ac3a746b6853a to your computer and use it in GitHub Desktop.
Demonstration of various classes in R
# dataframes vs lm S3 vs Bioc S4
# Michael Love
# Nov 1 2023
dat <- data.frame(genotype=c("wt","wt","mut","mut"),
count=c(10,20,30,40),
score=c(-1.2,0,3.4,-5),
gene=c("Abc","Abc","Xyz","Xyz"))
library(tibble)
dat |> as_tibble()
dat <- dat |> as_tibble()
# linear regression
lm(score ~ count, data=dat)
fit <- lm(score ~ count, data=dat)
class(fit)
methods(class="lm")
names(fit)
fit$coefficients
summary(fit)
library(broom)
fit |> tidy()
fit |> glance()
library(dplyr)
library(tidyr)
library(purrr)
sim <- tibble(g=rep(1:3,each=30),y=rnorm(90),x=rnorm(90))
sim |>
nest(.by=g) |>
mutate(fit = map(data, \(d) lm(y ~ x, data=d)),
stats = map(fit, glance)) |>
unnest(stats)
# Bioconductor objects have:
# slots, validation, special methods (dispatch)
library(SummarizedExperiment)
x <- list(counts=matrix(1:4 * 10, ncol=2),
score=matrix(-2:1, ncol=2))
rowdata <- data.frame(gene=c("Abc","Xyz"))
coldata <- data.frame(genotype=c("wt","mut"))
rownames(x[[1]]) <- rownames(x[[2]]) <- rowdata$gene
colnames(x[[1]]) <- colnames(x[[2]]) <- coldata$genotype
se <- SummarizedExperiment(assays=x, rowData=rowdata, colData=coldata)
assay(se, "counts")
rowData(se)
colData(se)
class(se)
methods(class = class(se))
slotNames(se)
se_sub <- se[ , se$genotype == "wt" ]
assay(se_sub, "counts")
# validation
rowdata2 <- rowdata
rownames(rowdata2) <- c("Xyz","Abc")
SummarizedExperiment(assays=x, rowData=rowdata2, colData=coldata)
# special methods
cbind(se, se)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment