jamie
jamie

Reputation: 13

need help simplify, repetition code

function(q,b,Data1,Data2){  
x<-sum(
  ifelse(Data1[13+q,b]/Data1[12+q,b]>Data2[13+q,1]/Data2[12+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[11+q,b]>Data2[13+q,1]/Data2[11+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[10+q,b]>Data2[13+q,1]/Data2[10+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[9+q,b]>Data2[13+q,1]/Data2[9+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[8+q,b]>Data2[13+q,1]/Data2[8+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[7+q,b]>Data2[13+q,1]/Data2[7+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[6+q,b]>Data2[13+q,1]/Data2[6+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[5+q,b]>Data2[13+q,1]/Data2[5+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[4+q,b]>Data2[13+q,1]/Data2[4+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[3+q,b]>Data2[13+q,1]/Data2[3+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[2+q,b]>Data2[13+q,1]/Data2[2+q,1],1,0)+
  ifelse(Data1[13+q,b]/Data1[1+q,b]>Data2[13+q,1]/Data2[1+q,1],1,0)
)/12
}

Is there a way to simplify this? (no characters, only numbers in the data sets)

Thank you

Upvotes: 0

Views: 79

Answers (2)

KenHBS
KenHBS

Reputation: 7164

Two pieces of knowledge you can combine to improve your code:

Firstly, you can divide a single number by a vector and R will return a vector with elementwise divisions. For example:

5 / c(1,2,3,4,5,6)
# [1] 5.0000000 2.5000000 1.6666667 1.2500000 1.0000000 0.8333333

The numerator on both sides of the inequality are the same all the time, you can use the above. So instead of explicitly calling it for every inequality, you can just call it once.

Secondly, an expression with TRUE or FALSE will be coerced to 1 and 0 when you try to perform arithmetic operations (in your case division, or calculating a mean). Inequalities return TRUE or FALSE values. Explicitly telling R to convert them to 0 and 1 is wasted energy, because R will automatically do it in your last step.

Putting this together in a simplified function:

function(q, b, Data1, Data2){
  qseq <- (1:12) + q   # Replaces all "q+1", "q+2", ... , "q+12"

  dat1 <- Data1[qseq, b]  # Replaces all "Data1[q+1, b]", ... "Data1[q+12, b]"
  dat2 <- Data2[qseq, 1]  # Replaces all "Data2[q+1, 1]", ... "Data2[q+12, 1]"

  mean( Data1[13+q, b]/dat1 > Data2[13+q, 1]/dat2 )

Upvotes: 2

timat
timat

Reputation: 1500

this simplify a bit:

function(q,b,Data1,Data2){  
    data1_num <- Data1[13+q,b]
    data2_num <- Data2[13+q,1]
    x <- 0 
    for (i in 1:12) {
        x <- x + ((data1_num/Data1[i+q,b]) > (data2_num /Data2[i+q,1]))
    } 
    x <- x /12
    #return(x)
}

But If you provide data example, and the output your expecting, i'm sure there is way to simplify it better

Upvotes: 0

Related Questions