0

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

Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

3 Answers3

1

Base R

df[abs(df) > 0.5] <- "duck"
Wimpel
  • 26,031
  • 1
  • 20
  • 37
1

Using replace:

replace(df,abs(df)>0.5,"duck")
Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46
1

A dplyr solution:

df %>% 
  mutate_all(funs(ifelse(abs(.) > .5, "duck", .)))
tmfmnk
  • 38,881
  • 4
  • 47
  • 67