I looked at multiple answers on Stackoverflow, but I stil couldn’t fix my problem. I made a function that works, but I added something and now it won’t work anymore. I want to replace all NA’s to 0, which seems simple to me.
This is my function, and I added bframe[is.na(bframe)] <- 0
:
B <- function(frame1, frame2, column){ bframe <- merge(frame 1, frame2, by = column, all = TRUE) bframe$result <- bframe$freq.x - bframe$freq.y bframe$percentage <- (bframe$result/bframe$freq.y)*100 bframe[is.na(bframe)] <- 0 return(bframe) } B(DT2_1, 2_1, "BurgS")
However, it gives this error: Error in '[<-.data.frame'('* tmp *, thisvar, value = 0) : duplicate subscripts for columns
.
The error occurs because there are NAs and it cannot perform the calculations:
BurgS freq.x freq.y result percentage percentageABS 1 9204 184042 -174838 -94.99897 94.99897 2 150 3034 -2884 -95.05603 95.05603 3 130 2602 -2472 -95.00384 95.00384 98 NA 47 NA NA NA
Not every data frame has this structure, so I am looking for a solution that changes NA’s in the whole data set. Can someone help me out?
Changed 26/6/2018: I stumbled up the solution myself. The code is as follows, so that the NA
of freq.x
is changed to 0 and still can be part of the calculations which the outcome is shown in the last three columns:
B <- function(frame1, frame2, column){ bframe$freq.x[is.na(bframe$freq.x)] <- 0 bframe <- merge(frame 1, frame2, by = column, all = TRUE) bframe$result <- bframe$freq.x - bframe$freq.y bframe$percentage <- (bframe$result/bframe$freq.y)*100 return(bframe) } B(DT2_1, 2_1, "BurgS")