R语言 本机管道使用下划线无效

apeeds0o  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(140)

示例:

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

看起来像:

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

我想用0替换整个df中的所有NA。我读了this blog post,然后尝试:

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"

我如何用这种方式在我的dplyr链中将我的df中的所有NA替换为0?

hjzp0vay

hjzp0vay1#

占位符(_)在本机管道中只能使用一次。
mydf |> replace(is.na(_), 0)中,已经将mydf作为replace的第一个参数传递,因此不能在is.na(_)中再次使用它。
您可以使用匿名函数调用。

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 -我相信你知道mydf[is.na(mydf)] <- 0 *

有趣的阅读What are the differences between R's new native pipe |> and the magrittr pipe %>%?

相关问题