0

I have a data frame that looks like this

df <- data.frame(col1=c("A","B","C","D"), col2=c(0,0,0,1))
df 
   col1 col2
1    A    0
2    B    0
3    C    0
4    D    1

I would like to replace each 0 in the col2 with 0.00000001 Is that possible to do it with the replace function in dplyr?

I want my data.frame to look like this

    col1 col2
1    A    0.00000001
2    B    0.00000001
3    C    0.00000001
4    D    1

4 Answers 4

3

Using dplyr:

df %>%
  mutate(col2 = replace(col2, col2 == 0, 0.0000001))

Using data.table:

dt <- data.table(df)
dt[col2 == 0, col2 := 0.00000001]
Sign up to request clarification or add additional context in comments.

Comments

2

Another way with simple ifelse

df %>%
  mutate(col2=ifelse(col2==0,0.00000001, col2))

Comments

2

For completion, here is a base R method

df$col2[df$col2 == 0] <- 0.00000001 
df

#  col1       col2
#1    A 0.00000001
#2    B 0.00000001
#3    C 0.00000001
#4    D 1.00000000

Comments

1
library(tidyverse)
df <- data.frame(col1=c("A","B","C","D"), col2=c(0,0,0,1))
df %>% 
  mutate(col2 = ifelse(col2 == 0, 0.00000001, col2))
#>   col1  col2
#> 1    A 1e-08
#> 2    B 1e-08
#> 3    C 1e-08
#> 4    D 1e+00

Created on 2021-09-10 by the reprex package (v2.0.1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.