如何在 R 函数中传递需要引号的参数?
How to pass an argument which needs quotes in an R function?
这是引用的非功能部分。效果不错。
library(countrycode)
countrycode(df$iso, origin = 'iso3c', destination = 'country.name')
我想把它放在一个函数中,但遇到了麻烦,因为国家代码函数无法识别没有 'quotes' 的参数。
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
func(df$iso, iso3c, country.name)
我该如何解决?
对于未加引号的输入,转换为在 base R
中使用 subsitute/deparse
加引号
func <- function(df, ori, dest) {
ori <- deparse(subsitute(ori)
dest <- deparse(subsitute(dest)
countrycode(df, origin = ori, destination = dest)
}
如果在父环境中定义了变量 iso3c
和 country.name
,您的函数就可以工作...
library(countrycode)
df <- data.frame(iso = c("USA", "DEU"))
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
iso3c <- "iso3c"
country.name <- "country.name"
func(df$iso, iso3c, country.name)
# [1] "United States" "Germany"
但您可能想要的是将字符串值本身传递给参数(而不是变量名,后者可能不存在)...
library(countrycode)
df <- data.frame(iso = c("USA", "DEU"))
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
func(df$iso, "iso3c", "country.name")
# [1] "United States" "Germany"
这是引用的非功能部分。效果不错。
library(countrycode)
countrycode(df$iso, origin = 'iso3c', destination = 'country.name')
我想把它放在一个函数中,但遇到了麻烦,因为国家代码函数无法识别没有 'quotes' 的参数。
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
func(df$iso, iso3c, country.name)
我该如何解决?
对于未加引号的输入,转换为在 base R
subsitute/deparse
加引号
func <- function(df, ori, dest) {
ori <- deparse(subsitute(ori)
dest <- deparse(subsitute(dest)
countrycode(df, origin = ori, destination = dest)
}
如果在父环境中定义了变量 iso3c
和 country.name
,您的函数就可以工作...
library(countrycode)
df <- data.frame(iso = c("USA", "DEU"))
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
iso3c <- "iso3c"
country.name <- "country.name"
func(df$iso, iso3c, country.name)
# [1] "United States" "Germany"
但您可能想要的是将字符串值本身传递给参数(而不是变量名,后者可能不存在)...
library(countrycode)
df <- data.frame(iso = c("USA", "DEU"))
func <- function(df, ori, dest) {
countrycode(df, origin = ori, destination = dest)
}
func(df$iso, "iso3c", "country.name")
# [1] "United States" "Germany"