Sebastian Cor
Sebastian Cor

Reputation: 105

The condition has length greater than 1 in function evaluation

I have this two functions:

Hwave<-function(t){
  if((0<=t & t<=1/2)){
    resultado<-t
  }else if((1/2<t & t<=1)){
    resultado<-1-t
  }else {resultado<-0}
  
  print(resultado)
}

And Im trying to create a new table of data by evaluating some data I have in the following way:

v<-c()
for(i in 0:(length(data)-1)){append(v,Hwave(data[i]),i)}

Then the condition has length greater than 1 error appears, but data[i] is a vector of length 1 for every entry so I don't know what is going wrong. Any help is appreciated.

The test data im using is data<-seq(from=0,to=1,by=2^(-8))

Upvotes: 0

Views: 204

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

You should have i in the for loop fall within the range 1 to length(data), e.g.,

v <- c()
for (i in 1:length(data)) {
  append(v, Hwave(data[i]), i)
}

since data[0] will give a syntax error.


Here is another workaround with vectorized version of Hwave, named as Hwave_1

Hwave_1 <- function(t) {
  ifelse(0 <= t & t <= 1 / 2, t, ifelse(1 / 2 < t & t <= 1, 1 - t, 0))
}

and you can try running Hwave_1 over data without any loops

Hwave_1(data)

Upvotes: 2

Related Questions