gpt4 book ai didi

处理向量的 R 函数

转载 作者:行者123 更新时间:2023-12-04 11:23:12 25 4
gpt4 key购买 nike

我有一个接受一个参数并打印一个字符串的函数:

test <- function(year){
print(paste('and year in (', year,')'))
}

我输入一个包含一个元素年份(2012)的向量,它会打印出这个:

"and year in ( 2012 )"

如果我输入 test(c(2012,2013,2014)),我该如何编写函数,它会打印出这个?

"and year in ( 2012,2013,2014 )"

最佳答案

您可以尝试使用 ellipsis任务,并将其包装在 toString 中,因为它可以接受无限量的值并同时对所有值进行操作。

test <- function(...){
print(paste('and year in (', toString(c(...)),')'))
}

test(2012:2014)
## [1] "and year in ( 2012, 2013, 2014 )"

这种方法的优点是它也适用于这样的输入

test(2012, 2013, 2014)
## [1] "and year in ( 2012, 2013, 2014 )"

关于处理向量的 R 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31923632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com