更新:我现在应该已经使用 ensym() 和 assign 函数解决了你的问题。
本质上,我们希望使用传递给函数的名称来访问全局变量。为了做到这一点,我们用 ensym 捕获它的名称而不是它的内容,然后我们使用 assign 函数分配它,我们告诉我们正在寻找的对象在全局环境中,并且具有我们用 ensym 存储的名称。
这是一个简单的解释,说明它是如何工作的。
library(rlang)
f <- function(x) {
x <- ensym(x)
assign(as_string(x), 2, envir = globalenv())
}
john <- 1
f(john)
print(john)
#> [1] 2
由reprex package (v2.0.0) 于 2021-04-05 创建
对于您的功能,我们希望采用这种方法:
library(rlang)
tuits <- function(x, y) {
# Get the name of the variable we want to store
x <- ensym(x)
tmp <- search_tweets(y, n=5000, include_rts = FALSE, lang = "es",
since = since, until = until) %>%
filter(screen_name != y)
# Assign the value to the variable in the global environment
assign(as_string(x), tmp, envir = globalenv())
}
tuits(Juan, "JuanPerez")
# to test
print(Juan)
旧答案(在上一节中改进)
我认为这里的问题是理解范围或环境的问题。如果在函数使用的环境或函数的 sdcope 中修改或设置对象,则只能在函数内以该形式访问它。
通常,函数的作用域包含在函数语句中分配的变量。
通常解决这个问题的方法是使用 return(x) 返回对象并将函数调用设置为对象。
tuits <- function(x, y) {
x <- search_tweets(y, n=5000, include_rts = FALSE, lang = "es",
since = since, until = until) %>%
filter(screen_name != y)
return(x)
}
Juan <- tuits(Juan, "JuanPerez")
您可以使用超赋值 (
超级赋值修改全局范围内的变量。但是,这会将值分配给 x 而不是对象。
tuits <- function(x, y) {
x <<- search_tweets(y, n=5000, include_rts = FALSE, lang = "es",
since = since, until = until) %>%
filter(screen_name != y)
}
tuits(Juan, "JuanPerez")