我在函数中有几个向量,它们的长度都相同(2000年)。我想用if语句检查一个向量中是否满足某些条件,然后代码应该对同一行中其他向量的项进行几次计算。到目前为止,我无法使用常规的if语句或ifelse函数来解决它。可以通过循环来解决,但是由于有2000次观察,这将导致代码的运行时间较长-我想避免这种情况。 我的代码如下:
function1 = function(vec1,vec3,vec4,vec5){
ifelse(vec5 < 20,
# Calculations follow which should be executed when the statement is true
# The row used for vec1 and vec3 should be the same as the row which got
# checked for vec5
a <- vec1 * 2 * vec3
b <- vec1 * 4
c <- cbind(a,b)
d<- apply(c, 1, FUN=min),
# Now should be the calculations if the if-statement is false
# Again, the row used for vec1, vec3 and vec 4 should be the same as the row
# which got checked for vec5
a <- vec1 * 2 * vec3
b <- vec1 * 4
c <- cbind(a,b)
d1<- apply(c, 1, FUN=min)
a2 <- vec1 * 1.5 * vec4
b2 <- vec1 * 4
c2 <- cbind(a2,b2)
d2<- apply(c2, 1, FUN=min)
d = d1 + d2) # end of ifelse
return(d)
}
# For convenience lets just assume the vectors are of length 3
vec1 <- c(100,150,120)
vec3 <- c(12,20,28)
vec4 <- c(42,48,43)
vec5 <- c(18,17,25)
d <- function1(vec1,vec3,vec4,vec5)
# d should be a vector of length 3 as well with outcome 400,600,960 if I calculated correctly by hand
此代码未运行,因为R似乎期望vec5 <20之后仅一行代码,而不是所有不同的计算。我怎么解决这个问题?感谢您的帮助!
答案 0 :(得分:3)
如果我正确理解,您的功能可以简化为
function1 <- function(vec1,vec3,vec4,vec5){
ifelse(vec5 < 20, pmin(vec1 * 2 * vec3, vec1 * 4),
pmin(vec1 * 2 * vec3, vec1 * 4) + pmin(vec1 * 1.5 * vec4,vec1 * 4))
}
function1(vec1, vec3, vec4, vec5)
#[1] 400 600 960
为了避免重复计算和ifelse
function1 <- function(vec1,vec3,vec4,vec5){
pmin(vec1 * 2 * vec3, vec1 * 4) +
(pmin(vec1 * 1.5 * vec4,vec1 * 4)*(vec5 >= 20))
}
function1(vec1, vec3, vec4, vec5)
#[1] 400 600 960