lapply 如何将寻址列作为未知变量?
How can lapply work with addressing columns as unknown variables?
所以,我有一个名为 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 无法识别这样的寻址列。有人可以帮忙吗?
这里有两种基本的 R 方法。数据集是 help("DGEList")
的例子和一个模型 data.frame sampleTable
.
定义 control_for
中 table 名称的矢量 common_vars
。然后创建新列。
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))
所以,我有一个名为 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 无法识别这样的寻址列。有人可以帮忙吗?
这里有两种基本的 R 方法。数据集是 help("DGEList")
的例子和一个模型 data.frame sampleTable
.
定义 control_for
中 table 名称的矢量 common_vars
。然后创建新列。
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))