如何在 for 循环中索引 R 对象?
How to index R objects within a for loop?
我正在尝试使用 for 循环来简化以下代码:
a1 <- CreateSeuratObject (raw.data = a1.data)
a2 <- CreateSeuratObject (raw.data = a2.data)
a3 <- ...
我试过以下方法:
samples <- c("a1", "a2", "a3")
samples.data <- c("a1.data", "a2.data", "a3.data")
for (i in samples) {
for (j in samples.data) {
i <- CreateSeuratObject(raw.data = j)
}
}
但是returns出现以下错误:
Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) :
'x' must be an array of at least two dimensions
CreateSeuratObject 函数本质上是尝试读取 samples.data 向量,而不是索引向量中的相应项目。我该如何解决这个问题?
您可以通过以下三种方式完成所需的操作。我建议你不要使用第一种方式。
samples <- c("a1", "a2", "a3")
samples.data <- c("a1.data", "a2.data", "a3.data")
for (i in seq_along(samples)) {
assign(samples[i], CreateSeuratObject(raw.data = samples.data[i]))
}
samples_list <- vector("list", length = length(samples))
for (i in seq_along(samples)) {
samples_list[[i]] <- CreateSeuratObject(raw.data = samples.data[i]))
}
names(samples_list) <- samples
samples_list2 <- lapply(samples.data, CreateSeuratObject)
names(samples_list2) <- samples
我正在尝试使用 for 循环来简化以下代码:
a1 <- CreateSeuratObject (raw.data = a1.data)
a2 <- CreateSeuratObject (raw.data = a2.data)
a3 <- ...
我试过以下方法:
samples <- c("a1", "a2", "a3")
samples.data <- c("a1.data", "a2.data", "a3.data")
for (i in samples) {
for (j in samples.data) {
i <- CreateSeuratObject(raw.data = j)
}
}
但是returns出现以下错误:
Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) :
'x' must be an array of at least two dimensions
CreateSeuratObject 函数本质上是尝试读取 samples.data 向量,而不是索引向量中的相应项目。我该如何解决这个问题?
您可以通过以下三种方式完成所需的操作。我建议你不要使用第一种方式。
samples <- c("a1", "a2", "a3")
samples.data <- c("a1.data", "a2.data", "a3.data")
for (i in seq_along(samples)) {
assign(samples[i], CreateSeuratObject(raw.data = samples.data[i]))
}
samples_list <- vector("list", length = length(samples))
for (i in seq_along(samples)) {
samples_list[[i]] <- CreateSeuratObject(raw.data = samples.data[i]))
}
names(samples_list) <- samples
samples_list2 <- lapply(samples.data, CreateSeuratObject)
names(samples_list2) <- samples