I have data in the following format in R:
Col1 Col2
1 1
2 1
4 0
0 0
2 2
. .
. .
. .
I’m using the following script to work out the percentage differences between Col1 & Col2 in each row.
temp <- matrix(numeric(),dim(data)[1],1)
for (i in 1:dim(data)[1])
{
temp[i,1]<- ((data[i,1]-data[i,2)/data[i,1])*100
}
For some reason my output file (temp) has some NA’s in it. They are occurring even when 0-0. Does anyone know why it isn’t just producing a 0 as opposed to NA? Some sums of 0-0 are producing a 0 as opposed to NA so I can’t see any real pattern.
Any help would be much appreciated. Thanks,
You are making the classic division by zero error. R reports this as
NaN– not a number, which is correct.One way to work around this is to use
ifelseto return zero wheneverCol==0:If you don’t want to use
with, then write your code like this (more verbose but identical):