Comfort Eagle
Comfort Eagle

Reputation: 2452

Conditional replacement of values in entire dataframe

What's the appropriate way to replace values within an entire data frame, without specifying rows or columns?

Let's assume that I'd like to replace all values where abs(x) > .5 by <- "duck"

In this case

> df <- data.frame(a = rnorm(5), b = rnorm(5), c = rnorm(5))
> df
            a          b          c
1  1.37481216 -0.1760366 -0.5122730
2  0.09204844 -0.4270991  0.3211998
3 -0.43563818  0.7560178  0.5399643
4 -0.02078887  0.5961020 -0.5985515
5  0.99129234 -0.9959395 -0.6488177

the desired output would be

            a          b          c
1  "duck"     -0.1760366  "duck"
2  0.09204844 -0.4270991  0.3211998
3 -0.43563818  "duck"     "duck"
4 -0.02078887  "duck"     "duck"
5  "duck"      "duck"     "duck"

While this post requires a specification of columns, I'm looking for a dynamic replacement for the entire data frame.

Thanks

Upvotes: 0

Views: 40

Answers (3)

Wimpel
Wimpel

Reputation: 27732

Base R

df[abs(df) > 0.5] <- "duck"

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

A dplyr solution:

df %>% 
  mutate_all(funs(ifelse(abs(.) > .5, "duck", .)))

Upvotes: 1

Saurabh Chauhan
Saurabh Chauhan

Reputation: 3221

Using replace:

replace(df,abs(df)>0.5,"duck")

Upvotes: 1

Related Questions