0

Example:

mydf <- data.frame(x = 1:10, y = rnorm(10))
mydf[2,2] <- NA
mydf[5,1] <- NA

Looks like:

mydf
    x          y
1   1 -1.0198834
2   2         NA
3   3  0.6080986
4   4 -0.4124830
5  NA  0.1723944
6   6 -2.3869210
7   7 -0.9843615
8   8 -1.3187416
9   9  0.1794670
10 10  0.9708277

I want to replace all NAs in the entire df with 0. I read this blog post then tried:

mydf |> replace(is.na(_), '') # Error in replace(mydf, is.na("_"), "") : invalid use of pipe placeholder
mydf |> mutate(across(everything(), .fns = ~replace_na(_, 0))) # Error in mydf |> mutate(across(everything(), .fns = ~replace_na("_", 0))) : invalid use of pipe placeholder

mydf |> mutate(across(everything(), .fns = ~replace_na(data = _, 0))) # same error, tried passing placeholder to a named arg per the blog post "One thing that is different than the . placeholder is the fact that you need to pass the name of the argument that will receive the _ placeholder"

How can I replace all NA with 0 in my df within my dplyr chain in this way?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

4

The placeholder (_) can be used only once in native pipe.

In mydf |> replace(is.na(_), 0) you are already passing mydf as first argument of replace so you cannot use it again in is.na(_).

You may use an anonymous function call.

mydf |> (\(x) replace(x, is.na(x), 0))()

#    x           y
#1   1 -0.02299403
#2   2  0.00000000
#3   3  0.29872957
#4   4 -0.78494209
#5   0  1.00703929
#6   6 -0.86201001
#7   7  1.26448247
#8   8  0.25913254
#9   9  1.69794293
#10 10  1.28005887

PS - I am sure you are aware of mydf[is.na(mydf)] <- 0

Interesting read What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213