R 如何通过将列名作为参数传递而不每次指定数据来创建函数?
我有两个问题:R 如何通过将列名作为参数传递而不每次指定数据来创建函数?,r,R,我有两个问题: 我想通过传递列名来创建一个函数(我得到了这个错误:“$”中的错误。默认值(“$”dat,“var”):$运算符对原子向量无效) 然后,我想创建一个函数,而不必每次都指定数据(我尝试使用attach(dat),但不起作用) 我正在尝试创建一个函数,允许用户输入数据集和列名 这是我试图创建的函数' fre <- function(dat, var) { abc <- questionr::na.rm(dat$var)
错误。默认值(“$”dat,“var”):$运算符对原子向量无效
)attach(dat)
,但不起作用)fre <- function(dat, var) {
abc <- questionr::na.rm(dat$var)
abc <- questionr::freq(abc)
abc <- cbind(Label = rownames(abc), abc)
abc <- questionr::rename.variable(abc, "n", "Frequency")
abc <- questionr::rename.variable(abc, "%", "Percent")
abc <- tidyr::separate(abc, Label, into = c("Value", "Label"), sep = "] ")
row.names(abc) <- NULL
abc <- abc %>% dplyr::mutate(Value = gsub("[[:punct:]]", '', Value)) %>% dplyr::select(Label, Value, Frequency, Percent)
abc
}
但我得到了一个错误:
Error in `$.default`(dat, "var") : $ operator is invalid for atomic vectors
我应该如何在此函数中传递列名以使其工作?
我根据r2evans的评论尝试了
var,结果如下:
fre <- function(dat, var) {
abc <- questionr::na.rm(dat[[var]])
abc <- questionr::freq(abc)
abc <- cbind(Label = rownames(abc), abc)
abc <- questionr::rename.variable(abc, "n", "Frequency")
abc <- questionr::rename.variable(abc, "%", "Percent")
abc <- tidyr::separate(abc, Label, into = c("Value", "Label"), sep = "] ")
row.names(abc) <- NULL
abc <- abc %>% dplyr::mutate(Value = gsub("[[:punct:]]", '', Value)) %>% dplyr::select(Label, Value, Frequency, Percent)
abc
}
fre(dat, "Q01")
fre你其实不需要太多的黑魔法。我已经制作了两个版本的函数
fre_pipe
需要数据作为输入参数,但它可以与管道一起使用
fre_free
依赖于名为global_dat
的对象,该对象必须在调用环境中定义
这里不需要enquo
,因为不需要捕获变量的环境ensym
就足够了(它确保您的var
被视为一个符号而不被执行)。在第二步中,可以使用as_string
将其转换为字符串。有关更多信息,请参阅高级R中的
图书馆(避风港)
图书馆(提问者)
图书馆(dplyr)
图书馆(tidyr)
#加载数据
dat%
purrr::walk(~print(fre(dat=dat,var=0.x)))
(但是这里普通的c(Q01,Q02)
不起作用,您需要创建一个函数来创建符号向量或使用列名。)dat[[var]]
,而不是dat$var
。(为此,请参见)var
必须是字符串,而不是符号。如果您习惯于不引用变量名的简洁方式,那么。。。为它编写函数更难。fre(dat,“Q01”)
或读取并掌握。
Error in `$.default`(dat, "var") : $ operator is invalid for atomic vectors
fre <- function(dat, var) {
abc <- questionr::na.rm(dat[[var]])
abc <- questionr::freq(abc)
abc <- cbind(Label = rownames(abc), abc)
abc <- questionr::rename.variable(abc, "n", "Frequency")
abc <- questionr::rename.variable(abc, "%", "Percent")
abc <- tidyr::separate(abc, Label, into = c("Value", "Label"), sep = "] ")
row.names(abc) <- NULL
abc <- abc %>% dplyr::mutate(Value = gsub("[[:punct:]]", '', Value)) %>% dplyr::select(Label, Value, Frequency, Percent)
abc
}
fre(dat, "Q01")