Reputation: 3088
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
Upvotes: 0
Views: 1879
Reputation: 388972
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
Upvotes: 2
Reputation: 8880
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)
Upvotes: 1
Reputation: 1332
Another way with simple ifelse
df %>%
mutate(col2=ifelse(col2==0,0.00000001, col2))
Upvotes: 2
Reputation: 2783
Using dplyr
:
df %>%
mutate(col2 = replace(col2, col2 == 0, 0.0000001))
Using data.table
:
dt <- data.table(df)
dt[col2 == 0, col2 := 0.00000001]
Upvotes: 3