LDT
LDT

Reputation: 3088

How can I replace a numeric value with another numeric value in a data frame with dplyR

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

Answers (4)

Ronak Shah
Ronak Shah

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

Yuriy Saraykin
Yuriy Saraykin

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

Shibaprasad
Shibaprasad

Reputation: 1332

Another way with simple ifelse

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

Upvotes: 2

koolmees
koolmees

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

Related Questions