Jack Armstrong
Jack Armstrong

Reputation: 1239

Fill in cell data for column in R

I have a two columns. I want to take col1/col2, but sometimes the value in col2 is 0. How can I change it to be 1. I thought I could create a function that ran an if statement, but that doesn't seem to be working.

Upvotes: 1

Views: 24

Answers (1)

akrun
akrun

Reputation: 887193

We can use a simple assignment

df1$col2[df1$col2==0] <- 1

or with ifelse

df1$col2 <- with(df1, ifelse(col2 == 0, 1, col2))

and then do the division


Or if it is only for division and not to change the values permanently

with(df1, col1/(pmax(1, col2)))

assuming there are no negative values and the values are integers

data

df1 <- data.frame(col1 = 1:5, col2 = c(0, 1, 2, 0, 4))

Upvotes: 1

Related Questions