Roger
Roger

Reputation: 395

Replace columns less than a threshold to 0

I have a dataframe that has 200 columns. I want to use dplyr to clean the data so that every number less than 0.05 is replaced with 0. A sample df was pasted below.

df
0.07262
0.039885
0.090173
0.124043
0.09201
0.068309
0.146381
0.09127
0.060768
0.111031

This is the desired outcome.

df
0.07262
0
0.090173
0.124043
0.09201
0.068309
0.146381
0.09127
0.060768
0.111031

This is my code: df2 <- mutate_all(ifelse(<0.05,0.,)) but it doesn't work. Any guidance is welcome.

Upvotes: 0

Views: 1587

Answers (3)

teller.py3
teller.py3

Reputation: 844

dplyr:

df <- mutate_all(df, funs(ifelse(. < 0.5, 0, .)))

base R:

df[df < 0.05] <- 0

Upvotes: 1

Kerry Jackson
Kerry Jackson

Reputation: 1871

Using dplyr, you can define the function before and then call it in the mutate_all

smallToZero <- function(x) {if_else(x<.05, 0, x)}
df2 <- 
  df %>% 
  mutate_all(smallToZero)

You can also have it as an un-named function using . as:

df2 <- 
  df %>% 
  mutate_all(funs(if_else(.<.05, 0, .)))

Upvotes: 1

Shree
Shree

Reputation: 11140

Here's one way using base R

  df[df < 0.05] <- 0

Upvotes: 3

Related Questions