问题描述
非常基本,但我认为我并没有真正理解变化:
Pretty basic but I don't think I really understand the change:
library(dplyr)
library(lubridate)
Lab_import_sql <- Lab_import %>%
select_if(~sum(!is.na(.)) > 0) %>%
mutate_if(is.factor, as.character) %>%
mutate_if(is.character, funs(ifelse(is.character(.), trimws(.),.))) %>%
mutate_at(.vars = Lab_import %>% select_if(grepl("'",.)) %>% colnames(),
.funs = gsub,
pattern = "'",
replacement = "''") %>%
mutate_if(is.character, funs(ifelse(is.character(.), paste0("'", ., "'"),.))) %>%
mutate_if(is.Date, funs(ifelse(is.Date(.), paste0("'", ., "'"),.)))
感谢大家的输入,这里是可重现的代码和我的解决方案:
Thanks everyone for the input, here's reproducible code and my solution:
library(dplyr)
library(lubridate)
import <- data.frame(Test_Name = "Fir'st Last",
Test_Date = "2019-01-01",
Test_Number = 10)
import_sql <-import %>%
select_if(~!all(is.na(.))) %>%
mutate_if(is.factor, as.character) %>%
mutate_if(is.character, trimws) %>%
mutate_if(is.character, list(~gsub("'", "''",.))) %>%
mutate_if(is.character, list(~paste0("'", ., "'"))) %>%
mutate_if(is.Date, list(~paste0("'", ., "'")))
推荐答案
从 dplyr
0.8.0 开始,documentation 指出我们应该使用 list
而不是 funs
,举个例子:
As of dplyr
0.8.0, the documentation states that we should use list
instead of funs
, giving the example:
之前:
funs(name = f(.))
之后:
list(name = ~f(.))
所以在这里,调用 funs(ifelse(is.character(.), trimws(.),.))
可以变成 list(~ifelse(is.character(.),trimws(.),.))
.这是在 tidyverse
中使用匿名函数的公式符号,其中单边公式(以 ~
开头的表达式)被解释为 function(x)
,而 x
在函数中的位置由 .
表示.您仍然可以使用 list
中的全部功能.
So here, the call funs(ifelse(is.character(.), trimws(.),.))
can become instead list(~ifelse(is.character(.), trimws(.),.))
. This is using the formula notation for anonymous functions in the tidyverse
, where a one-sided formula (expression beginning with ~
) is interpreted as function(x)
, and wherever x
would go in the function is represented by .
. You can still use full functions inside list
.
注意 mutate_if
的 .funs
参数和包装其他函数以传递给 的
;即 funs()
函数之间的区别.funs.funs = gsub
仍然有效.如果您需要将多个函数应用于选定的列或通过将它们作为命名参数传递来命名它们,则只需要 funs()
.你可以用 list()
做同样的事情.
Note the difference between the .funs
argument of mutate_if
and the funs()
function which wrapped other functions to pass to .funs
; i.e. .funs = gsub
still works. You only needed funs()
if you needed to apply multiple functions to selected columns or to name them something by passing them as named arguments. You can do all the same things with list()
.
您还通过在 mutate_if
中添加 ifelse
来重复工作;该行可以简化为 mutate_if(is.character, trimws)
因为如果该列已经是字符,则您不需要使用 ifelse
再次检查它.由于您只应用一个函数,因此根本不需要 funs
或 list
.
You also are duplicating work by adding ifelse
inside mutate_if
; that line could be simplified to mutate_if(is.character, trimws)
since if the column is character already you don't need to check it again with ifelse
. Since you apply only one function, no need for funs
or list
at all.
这篇关于如何更改现在已弃用的包含 ifelse 参数的 dplyr::funs()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!