使用 for 循环附加可变长度的向量
Using for loop to append vectors of variable length
我正在尝试根据对列的各个元素执行的函数的输出创建一个向量或值列表。
library(hpoPlot)
xyz_hpo <- c("HP:0003698", "HP:0007082", "HP:0006956")
getallancs <- function(hpo_col) {
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- list()
output[[length(anc) + 1]] <- append(output, anc)
}
return(anc)
}
all_ancs <- getallancs(xyz_hpo)
get.ancestors 根据每个术语输出可变长度的字符向量。如何循环 hpo_col 将每个 ancs 向量的长度添加到输出向量?
欢迎来到 Stack Overflow :) 提供最小的可重现示例真是太棒了!
如评论中所述,您需要将 output <- list()
移到 for
循环之外,并将 return 移到循环之后。目前它正在为循环的每次迭代重置,这不是您想要的。我还认为你想要 return 一个向量而不是一个列表,所以我改变了 output
.
的类型
此外,在你原来的问题中,你说你想 return 循环中每个 anc
向量的长度,所以我更改了函数以输出每次迭代的长度,而不是整个向量。
getallancs <- function(hpo_col) {
output <- numeric()
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- append(output, length(anc))
}
return(output)
}
如果您只是在少数情况下这样做,例如您的示例,这种方法会很好,但是,这种范式在 R 中通常很慢,最好尝试 vectorise 这种风格如果可能的话计算。如果您 运行 对于计算需要超过几秒钟的大量元素,这一点尤其重要。
例如,可以将上述函数矢量化的一种方式如下:
all_ancs <- sapply(xyz_hpo, function(x) length(get.ancestors(hpo.terms, x)))
如果实际上您的意思是输出 anc
的整个向量,而不仅仅是长度,则原始函数将如下所示:
getallancs <- function(hpo_col) {
output <- character()
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- c(output, anc)
}
return(output)
}
或者矢量化版本可以是
all_ancs <- unlist(lapply(xyz_hpo, function(x) get.ancestors(hpo.terms, x)))
希望对您有所帮助。如果解决了您的问题,请标记为答案。
我正在尝试根据对列的各个元素执行的函数的输出创建一个向量或值列表。
library(hpoPlot)
xyz_hpo <- c("HP:0003698", "HP:0007082", "HP:0006956")
getallancs <- function(hpo_col) {
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- list()
output[[length(anc) + 1]] <- append(output, anc)
}
return(anc)
}
all_ancs <- getallancs(xyz_hpo)
get.ancestors 根据每个术语输出可变长度的字符向量。如何循环 hpo_col 将每个 ancs 向量的长度添加到输出向量?
欢迎来到 Stack Overflow :) 提供最小的可重现示例真是太棒了!
如评论中所述,您需要将 output <- list()
移到 for
循环之外,并将 return 移到循环之后。目前它正在为循环的每次迭代重置,这不是您想要的。我还认为你想要 return 一个向量而不是一个列表,所以我改变了 output
.
此外,在你原来的问题中,你说你想 return 循环中每个 anc
向量的长度,所以我更改了函数以输出每次迭代的长度,而不是整个向量。
getallancs <- function(hpo_col) {
output <- numeric()
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- append(output, length(anc))
}
return(output)
}
如果您只是在少数情况下这样做,例如您的示例,这种方法会很好,但是,这种范式在 R 中通常很慢,最好尝试 vectorise 这种风格如果可能的话计算。如果您 运行 对于计算需要超过几秒钟的大量元素,这一点尤其重要。
例如,可以将上述函数矢量化的一种方式如下:
all_ancs <- sapply(xyz_hpo, function(x) length(get.ancestors(hpo.terms, x)))
如果实际上您的意思是输出 anc
的整个向量,而不仅仅是长度,则原始函数将如下所示:
getallancs <- function(hpo_col) {
output <- character()
for (i in 1:length(hpo_col)) {
anc <- get.ancestors(hpo.terms, hpo_col[i])
output <- c(output, anc)
}
return(output)
}
或者矢量化版本可以是
all_ancs <- unlist(lapply(xyz_hpo, function(x) get.ancestors(hpo.terms, x)))
希望对您有所帮助。如果解决了您的问题,请标记为答案。