R语言 把输出转换成矢量

b09cbbtk  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(106)

这段代码打印了两个数组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 1RandomArraySeq 2,它们的值是那些随机序列。
当然,我说的是R编程语言,你可能已经注意到了。
我试过使用循环,但我不能。

9fkzdhlc

9fkzdhlc1#

让函数generateNTarrays返回一个命名向量,而不是返回一个成员为字符序列的列表。这也简化了打印代码。
请注意,seed没有在函数中使用,就像它没有在原始代码中一样。

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

编辑

下面的函数等价于上面的函数,但使用了R 4.1中引入的R原生管道操作符。

generateNTarrays <- function(num_arrays = 5, array_length = 5,
                             allowed_characters = c('A', 'T', 'C', 'G'), seed=123) {
  # output vector is a named vector
  arrays_names <- sprintf("RandomArraySeq_%d", seq_len(num_arrays))
  # create the vector and assign its names before returning to caller
  num_arrays |>
    replicate(sample(allowed_characters, array_length, replace = TRUE), simplify = FALSE) |> 
    sapply(paste, collapse = "") |>
    setNames(arrays_names)
}

相关问题