mercredi 27 juin 2018

R: Function stops after internal IF statement

I wrote a function to do some calculations with frequencies (of values in the dataframe) and put them in a new column. Some calculations cannot be perform if the value is NA, so I changed them to 0. Subsequently, because a value cannot be divided by 0, I want the outcome to be the first frequency.

Now, the function stops after the IF-statement inside the function. Can you guys see what is wrong with it, without the data?

B <- function(frame1, frame2, col){
    Bframe <- merge(frame1, frame2, by = column, all = TRUE)
    Bframe$freq.x[is.na(Bframe$freq.x)] <- 0 
    Bframe$freq.y[is.na(Bframe$freq.y)] <- 0 
    if (Bframe$freq.y == 0) { 
      Bframe$result <- Bframe$freq.x
    }
    Bframe$result <- Bframe["freq.x"] - Bframe["freq.y"]
    Bframe$percentage <- (Bframe["result"]/Bframe["freq.y])*100
    Bframe$percABS <- abs(Bframe$percentage)
    return(Bframe)
}

So, the function works up to Bframe$result. Is something in the structure wrong?

I also got an error: Warning message: In if (Bframe$freq.y == 0) {: the condition has length > 1 and only the first element will used.

If you do need some input data, please tell me.

Aucun commentaire:

Enregistrer un commentaire