[英]How to combine results of a for loop, inside a function, in to a character vector?
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"
The function returns 5 character vectors of length 1. I would like the function to return one vector of length 5 - in the order passed by in the arguments (A>B>C>D>E) 该函数返回5个长度为1的字符向量。我希望该函数返回一个长度为5的向量-按照参数中传递的顺序(A> B> C> D> E)
Your function actually doesn't return anything, it just prints the statements. 您的函数实际上不返回任何内容,而只是打印语句。 If you want to return something, this is an option:
如果您想退货,可以选择以下方法:
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"))
}))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.