I am trying to write an infix function called %#% that will operate on two vectors x and y. The operation x%#%y should return a vector that is the same length as x and y. Element i of the returned vector should be x[i]+y[i] if x[i]>0 and y[i]>0, 0 if x[i]>0 and y[i]<0 or if x[i]<0 and y[i]>0, and -x[i]-y[i] if x[i]<0 and y[i]<0. An error should be returned if the vectors have different lengths.
x <- rnorm(10)
y <- rnorm(10)
'%#%' <- function(x,y) {
for (i in 1:10)
{
if (x[i]>0 & y[i]>0) paste(x[i]+y[i])
if (x[i]>0 & y[i]<0) paste(0)
if (x[i]<0 & y[i]>0) paste(0)
if (x[i]<0 & y[i]<0) paste(-x[i]-y[i])
else stop("Vectors have different lengths")
}}
x%#%y
It just keeps giving me the error message.
I recommend to:
#
because this symbol is reserved for comments in Rx
or y
are zeroYou could try something along the lines:
`%ooo%` <- function(x,y) {
if(length(x)!=length(y))
stop("Vectors have different lengths")
tmp <- ifelse(x>0 & y>0, x+y, -x-y)
tmp[(x>0 & y<0) | (x<0 & y>0)] <- 0
tmp
}
x <- rnorm(10)
y <- rnorm(10)
rep(1, 5) %ooo% rep(1, 6)
## Error in rep(1, 5) %ooo% rep(1, 6) : Vectors have different lengths
rep(1, 5) %ooo% -2:2
## [1] 0 0 -1 2 3