I have several vectors in a function which are all of the same lengths (2000). I want to check with an if-statement whether some condition is met in one vector and then the code should do several calculations with the entries from the other vectors of the same row. So far, I could not solve it with the normal if-statement nor with the ifelse function. It could be solved with a loop but as I have 2000 observations, that would result in a long run-time of the code - which I would like to avoid. My code looks like:
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)
}
This code does not run as R seems to expect only one line of code after vec5<20 instead of all the different calculations. How can I solve this problem? Thanks for the help!
Aucun commentaire:
Enregistrer un commentaire