问题描述
相当基本,但我认为我不太了解更改:
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起,指出,我们应该改用 list
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(。),。))
c变成 list(〜ifelse(is.character(。),trimws(。),。))
。这是对 tidyverse
中匿名函数使用的公式表示法,其中一个单侧公式(以〜
开头的表达式)解释为 function(x)
,而 x
在函数中所处的位置由<$ c $表示。 c>。。您仍然可以在 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
.
请注意 .funs $ c之间的区别
mutate_if
的$ c>参数和 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()
.
您还可以通过添加 ifelse来复制工作。
位于 mutate_if
内;该行可以简化为 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.
这篇关于如何更改现已弃用的dplyr :: funs()(其中包含ifelse参数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!