【问题标题】:How to combine results of a for loop, inside a function, in to a character vector?如何在函数内部将 for 循环的结果组合到字符向量中?
【发布时间】:2018-12-19 17:25:28
【问题描述】:
my_function <- function(A,B,C,D,E) {
for (event in c(A,B,C,D,E)){
    if (event %in% c(A,E)) print(paste0(event, "foo"))
    if (event %in% c(B,C,D)) print(paste0(event, "bar"))
  }
}

my_function(45, 34, 23, 213, 134)
[1] "45foo"
[1] "34bar"
[1] "23bar"
[1] "213bar"
[1] "134foo"

该函数返回 5 个长度为 1 的字符向量。我希望该函数返回一个长度为 5 的向量 - 按照参数中传递的顺序 (A>B>C>D>E)

【问题讨论】:

  • 你的函数不返回任何东西,它只是打印。执行result = my_function(45, 34, 23, 213, 134),然后看到resultNULL。我假设您确实想返回一些东西,而不仅仅是打印结果,但我想确认一下。
  • @Gregor 你是对的

标签: r function for-loop concatenation


【解决方案1】:

您的函数实际上不返回任何内容,它只是打印语句。 如果你想退货,这是一个选项:

my_function <- function(A,B,C,D,E) {
  return(sapply(c(A,B,C,D,E),function(x){
    if(x %in% c(A,E)) return(paste0(x,"foo"))
    if(x %in% c(B,C,D)) return(paste0(x,"bar"))
  }))
}

【讨论】:

    猜你喜欢
    • 2017-07-03
    • 2019-04-09
    • 1970-01-01
    • 2021-03-11
    • 2023-01-29
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多