Dea12
Dea12

Reputation: 55

Division by 0 in r, avoid NaN

I have this code here:

d$ICER <- d$Delta_Cost/d$Delta_LY

I do this for each row, in a matrix in R, now, the first row has values of Delta_Cost and Delta_LY = 0, so ICER is 0/0 and gives me a value NaN.

How can I modify it to be 0 instead of NaN?

Upvotes: 2

Views: 12234

Answers (3)

Mike Khan
Mike Khan

Reputation: 595

While both answers here provide perfectly valid ways to solve the problem the question provides neither of them provide a warning against changing the NaNs to 0 so here you go.

If you plan on running any statistical analysis on your data, naively converting the NaNs to 0s will give you wrong answers.

Here is an extreme example to show you the problem:

> test <- c(1,2,3,4,5,NaN,NaN,NaN,NaN,NaN)
> test_zeros <- test
> test_zeros[is.na(test_zeros)] <- 0
> 
> mean(test)
[1] NaN
> mean(test_zeros)
[1] 1.5
> mean(test, na.rm = TRUE)
[1] 3
> 
> median(test)
[1] NA
> median(test_zeros)
[1] 0.5
> median(test, na.rm = TRUE)
[1] 3

The mean and median for test_zeros were not representative of the actual data. Using na.rm is a better alternative as it removes the rows with NaNs from the calculation altogether. This still has its problem and should be used with caution.

No matter which of the options you choose to use you should understand the effect it will have on your analysis.

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You can use ifelse:

d$ICER <- ifelse(!d$Delta_Cost, 0, d$Delta_Cost / d$Delta_LY)

Upvotes: 1

Pop
Pop

Reputation: 12411

You can do:

d$ICER <- d$Delta_Cost/d$Delta_LY
d$ICER[is.na(d$ICER)] <- 0

Upvotes: 3

Related Questions