r用户定义函数参数-什么可以定义为参数?
我正在尝试编写R函数,这些函数在SAS中执行与宏类似的任务,例如r用户定义函数参数-什么可以定义为参数?,r,function,dplyr,arguments,user-defined-functions,R,Function,Dplyr,Arguments,User Defined Functions,我正在尝试编写R函数,这些函数在SAS中执行与宏类似的任务,例如 过程变量 命名一个新变量 命名一个新的数据帧 我已经使用内置的df“iris”和dplyr尝试了一些基本功能,如下所示 函数f3和f4尝试接受变量名并对其进行处理。错误消息为“错误:未找到对象‘物种’”和“平均值。默认值(var):参数不是数字或逻辑参数:返回NA” 函数f5和f6尝试命名新变量或新df。运行函数后,新变量或df将以参数名称命名 f7尝试使用函数命名部分变量 library(dplyr) data(iris) v
library(dplyr)
data(iris)
view(iris)
### Char Variable
f3 <- function(var){
iris %>% filter(var == "setosa")
}
f3(Species)
f4 <- function(var){
iris %>% summarise(
avg = mean(var)
)
}
f4("Sepal.Length")
### Variable Name
f5 <- function(name){
iris %>%
mutate(name = 1)
}
f5("newname")
### df Name
f6 <- function(dfname){
dfname <- iris
}
f6("newdf")
f7 <- function(name){
test <- iris %>%
mutate(
v_name = 1
)
}
f7("1")
库(dplyr)
数据(iris)
视图(iris)
###字符变量
f3%过滤器(变量==“setosa”)
}
f3(物种)
f4%总结(
平均值=平均值(var)
)
}
f4(“萼片长度”)
###变量名
f5%
变异(名称=1)
}
f5(“新名称”)
###df名称
f6使用tidyverse
,如果我们通过unquote,它可以转换为quosure(rlang::enquo
)并求值(!!
),这是通过{}
卷曲操作符完成的
f3 <- function(var){
iris %>%
filter({{var}} == "setosa")
}
f3(Species)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
#...
如果要通过带引号或不带引号,请使用ensym
转换为符号并计算(!!
)
或使用f5
f5 <- function(name){
iris %>%
mutate(!! name := 1)
}
f5("newname")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species newname
#1 5.1 3.5 1.4 0.2 setosa 1
#2 4.9 3.0 1.4 0.2 setosa 1
#3 4.7 3.2 1.3 0.2 setosa 1
#4 4.6 3.1 1.5 0.2 setosa 1
# ..
非常感谢。f3和f4工作完美!但是curly-curly运算符不适用于其余函数。如果要在全局环境中分配新对象,请在f6中使用assign(dfname,iris,envir=.GlobalEnv)
f4 <- function(var){
iris %>%
summarise(
avg = mean(!! rlang::ensym(var))
)
}
f4(Sepal.Length)
# avg
#1 5.843333
f4("Sepal.Length")
# avg
#1 5.843333
library(stringr)
f7 <- function(name){
iris %>%
mutate(
!!str_c("v_", name) := 1
)
}
f7("1")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species v_1
#1 5.1 3.5 1.4 0.2 setosa 1
#2 4.9 3.0 1.4 0.2 setosa 1
#3 4.7 3.2 1.3 0.2 setosa 1
#4 4.6 3.1 1.5 0.2 setosa 1
#...
f5 <- function(name){
iris %>%
mutate(!! name := 1)
}
f5("newname")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species newname
#1 5.1 3.5 1.4 0.2 setosa 1
#2 4.9 3.0 1.4 0.2 setosa 1
#3 4.7 3.2 1.3 0.2 setosa 1
#4 4.6 3.1 1.5 0.2 setosa 1
# ..
f6 <- function(dfname){
assign(dfname, value = iris, envir = .GlobalEnv)
}
f6("newdf")
head(newdf, 2)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa