user1412 - 5 months ago 19

R Question

This might be very simple, but I am not able to get how to fix this problem. Basically I need to calculate growth for multiple columns. So when I am dividing by a column, if it has 0 value it returns **Inf**

Let me take a example data set

`a <- c(1,0,3,4,5)`

b <- c(1,4,2,0,4)

c <- data.frame(a,b)

c$growth <- b/a-1

So if you see for the 2nd row since a is having 0 the growth is Inf. It should display 4

My original data is in data.table so any solution in data.table would help.

How can we fix this?

Answer Source

I don't know why you want to turn Inf to 4. In my opinion it doesn't make any sense as the growth is not 4 is Inf. However, if you still want to do that here's some code:

```
a <- c(1,0,3,4,5)
b <- c(1,4,2,0,4)
data <- data.frame(a,b)
data$growth <- b/a-1
data[data$growth == Inf,3] <- data[data$growth == Inf,2]
```