Update: I now should have solved your problem using the ensym()
and assign
functions.
Essentially we want to access the global variable with the name passed to the function. In order to do this we capture its name not its contents with ensym and then we assign it using the assign function which we tell that the object we are looking for is in the global environment and has the name that we stored with ensym.
Here is a brief explanation showing how it works.
library(rlang)
f <- function(x) {
x <- ensym(x)
assign(as_string(x), 2, envir = globalenv())
}
john <- 1
f(john)
print(john)
#> [1] 2
Created on 2021-04-05 by the reprex package (v2.0.0)
For your function we would want to take this approach:
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)
Old Answer (improved on in the above section)
I believe the issue here is an issue of understanding scope or environments. If an object is modifed or set within the environment used by a function or the sdcope of the function then it can only be accessed in that form within the function.
Usually the scope of a function contains the variables that are assigned inside the function statement.
Usually the way to solve this would be to return the object using return(x) and setting the function call to the object.
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")
You could modify the object x using a superassignment (<<-) operation however this is usually not best practise. I will provide this solution for completeness sake.
Superassignment modifies the variable in the global scope. This however will assign the value to x not the object.
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")