示例:
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?
1条答案
按热度按时间hjzp0vay1#
占位符(
_
)在本机管道中只能使用一次。在
mydf |> replace(is.na(_), 0)
中,已经将mydf
作为replace
的第一个参数传递,因此不能在is.na(_)
中再次使用它。您可以使用匿名函数调用。
mydf[is.na(mydf)] <- 0
*有趣的阅读What are the differences between R's new native pipe
|>
and the magrittr pipe%>%
?