所以,我有一個名為control_for. 我有一個資料框sampleTable,其中一些列名為control_for串列中的字串。我有第三個物件dge_obj(DGElist 物件),我想在其中附加這些列。我想要做的 - 使用 lapply 回圈遍歷control_for串列,對于每個字串,在sampleTable其中找到一個具有相同名稱的列,然后將該列(作為一個因素)添加到 DGElist 物件中。例如,對于僅使用一個字串手動執行此操作,它看起來像這樣,并且可以正常作業:
group <- as.factor(sampleTable[,3])
dge_obj$samples$group <- group
我試過這樣的事情:
lapply(control_for, function(x) {
x <- as.factor(sampleTable[, x])
dge_obj$samples$x <- x
}
哪個不起作用。我想問題是 R 無法識別這樣的尋址列。有人可以幫忙嗎?
uj5u.com熱心網友回復:
這里有兩種基本的 R 方法。資料集是help("DGEList")data.frame的示例和模型sampleTable。
在 中定義common_vars表名稱的向量control_for。然后創建新列。
library(edgeR)
sampleTable <- data.frame(a = 1:4, b = 5:8, no = letters[21:24])
control_for <- c("a", "b")
common_vars <- intersect(control_for, names(sampleTable))
1.for回圈
for(x in common_vars){
y <- sampleTable[[x]]
dge_obj$samples[[x]] <- factor(y)
}
2.*apply回圈。
tmp <- sapply(sampleTable[common_vars], factor)
dge_obj$samples <- cbind(dge_obj$samples, tmp)
這段代碼可以重寫為單行代碼。
資料
set.seed(2021)
y <- matrix(rnbinom(10000,mu=5,size=2),ncol=4)
dge_obj <- DGEList(counts=y, group=rep(1:2,each=2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351656.html
上一篇:如何從觀星者輸出中洗掉模型型別?
下一篇:R-根據最近的匹配列查找和更新
