suppressWarnings() 不适用于管道运算符
suppressWarnings() doesn't work with pipe operator
我正在尝试使用 suppressWarnings()
函数来抑制警告。
令人惊讶的是,它在正常使用时会删除警告,但在您使用管道 %>%
运算符时却无法这样做。
这是一些示例代码:
library(magrittr)
c("1", "2", "ABC") %>% as.numeric()
# [1] 1 2 NA
# Warning message:
# In function_list[[k]](value) : NAs introduced by coercion
c("1", "2", "ABC") %>% as.numeric() %>% suppressWarnings
# [1] 1 2 NA
# Warning message:
# In function_list[[i]](value) : NAs introduced by coercion
suppressWarnings(c("1", "2", "ABC") %>% as.numeric())
# [1] 1 2 NA
为什么它使用圆括号而不使用管道运算符?
我应该使用特定的语法来使其工作吗?
一个解决方案是使用 %T>%
管道修改选项(来自 magrittr
,不包括在 dplyr
中!)
c("1", "2", "ABC") %T>% {options(warn=-1)} %>% as.numeric() %T>% {options(warn=0)}
您也可以使用 purrr::quietly
,在这种情况下不太漂亮...
library(purr)
c("1", "2", "ABC") %>% {quietly(as.numeric)}() %>% extract2("result")
c("1", "2", "ABC") %>% map(quietly(as.numeric)) %>% map_dbl("result")
为了完整起见,这里还有@docendo-discimus 的解决方案和 OP 自己的解决方法
c("1", "2", "ABC") %>% {suppressWarnings(as.numeric(.))}
suppressWarnings(c("1", "2", "ABC") %>% as.numeric())
我盗用了@Benjamin 关于为什么原来的尝试不起作用的评论:
Warnings are not part of the objects; they are cast when they occur,
and cannot be passed from one function to the next
编辑:
链接的解决方案将允许您只写 c("1", "2", "ABC") %W>% as.numeric
我正在尝试使用 suppressWarnings()
函数来抑制警告。
令人惊讶的是,它在正常使用时会删除警告,但在您使用管道 %>%
运算符时却无法这样做。
这是一些示例代码:
library(magrittr)
c("1", "2", "ABC") %>% as.numeric()
# [1] 1 2 NA
# Warning message:
# In function_list[[k]](value) : NAs introduced by coercion
c("1", "2", "ABC") %>% as.numeric() %>% suppressWarnings
# [1] 1 2 NA
# Warning message:
# In function_list[[i]](value) : NAs introduced by coercion
suppressWarnings(c("1", "2", "ABC") %>% as.numeric())
# [1] 1 2 NA
为什么它使用圆括号而不使用管道运算符? 我应该使用特定的语法来使其工作吗?
一个解决方案是使用 %T>%
管道修改选项(来自 magrittr
,不包括在 dplyr
中!)
c("1", "2", "ABC") %T>% {options(warn=-1)} %>% as.numeric() %T>% {options(warn=0)}
您也可以使用 purrr::quietly
,在这种情况下不太漂亮...
library(purr)
c("1", "2", "ABC") %>% {quietly(as.numeric)}() %>% extract2("result")
c("1", "2", "ABC") %>% map(quietly(as.numeric)) %>% map_dbl("result")
为了完整起见,这里还有@docendo-discimus 的解决方案和 OP 自己的解决方法
c("1", "2", "ABC") %>% {suppressWarnings(as.numeric(.))}
suppressWarnings(c("1", "2", "ABC") %>% as.numeric())
我盗用了@Benjamin 关于为什么原来的尝试不起作用的评论:
Warnings are not part of the objects; they are cast when they occur, and cannot be passed from one function to the next
编辑:
链接的解决方案将允许您只写 c("1", "2", "ABC") %W>% as.numeric