此代码打印两个名为 RandomArraySeq 1 和 RandomArraySeq 2 的数组,其中包含 5 个长度的随机序列,对吧?
generateNTarrays <- function(num_arrays = 5, array_length = 5,
allowed_characters = c('A', 'T', 'C', 'G'), seed=123) {
arrays <- replicate(num_arrays, sample(allowed_characters, array_length, replace = TRUE), simplify = F)
return(arrays)
}
print_arrays <- function(arrays) {
num_arrays <- length(arrays)
for (i in 1:num_arrays) {
cat(paste("RandomArraySeq", i, ":", paste(arrays[[i]], collapse = ""), "\n"))
}
}
# Call the functions outside of the definition
generated_arrays <- generateNTarrays(2,5)
print_arrays(generated_arrays)
控制台中的输出显示为:
RandomArraySeq 1:CCTGA
RandomArraySeq 2:AGGAA
现在我想要将输出作为对象,我的意思是有两个对象
RandomArraySeq 1
和 RandomArraySeq 2
,其值是那些随机序列。我尝试使用循环,但不能。
让函数
generateNTarrays
返回一个命名向量,而不是返回一个成员为字符序列的列表。这也简化了打印代码。
generateNTarrays <- function(num_arrays = 5, array_length = 5,
allowed_characters = c('A', 'T', 'C', 'G'), seed=123) {
arrays <- replicate(num_arrays, sample(allowed_characters, array_length, replace = TRUE), simplify = FALSE)
arrays <- sapply(arrays, paste, collapse = "")
arrays_names <- sprintf("RandomArraySeq_%d", seq_along(arrays))
setNames(arrays, arrays_names)
}
print_arrays <- function(arrays) {
for (i in seq_along(arrays)) {
cat(names(arrays)[i], ":", arrays[i], "\n")
}
}
# Call the functions outside of the definition
generated_arrays <- generateNTarrays(2,5)
generated_arrays
#> RandomArraySeq_1 RandomArraySeq_2
#> "ACCCA" "TTTTC"
print_arrays(generated_arrays)
#> RandomArraySeq_1 : ACCCA
#> RandomArraySeq_2 : TTTTC
创建于 2023-09-16,使用 reprex v2.0.2