Return elements of list as independent objects in global environment
There is special function for mapping list to environment:
> obj <- list(a=1:5, b=2:10, c=-5:5)
> ls()
[1] "obj"
> list2env(obj,globalenv())
<environment: R_GlobalEnv>
> ls()
[1] "a" "b" "c" "obj"
P. S. It is my comment provided as an answer
Global assignment of list elements within a function, using a variable name for the list
First of all, I'll be clear that I do not encourage assigning values to variables from inside the function in global environment. Ideally, you should always return
the value from the function which you want to change. However, just for demonstration purpose here is a way in which you can change the contents of the list from inside the function
my_fun <- function(some_list) {
list_name <- deparse(substitute(some_list))
some_list[[1]] <- 'element_assigned_in_function'
assign(list_name, some_list, .GlobalEnv)
}
my_list <- list('original_element')
my_fun(my_list)
my_list
#[[1]]
#[1] "element_assigned_in_function"
Make list of objects in global environment matching certain string pattern
I have used the following, obviously this will need to be repeated for each pattern.
Pattern1<-grep("local",names(.GlobalEnv),value=TRUE)
Pattern1_list<-do.call("list",mget(Pattern1))
How can I source a file into a list in the global environment
I think you have a misconception: if foo
is stored in your list p
, then redefining foo
in .Globalenv
won't have any effect. Those will be separate objects.
The purpose of the environment associated with a function is to tell R where to look for non-local variables used in the function. Your original version will end up with two copies of everything you sourced, one in the list and one in the local environment you created. If foo
referred to x
, it would see the one in the local environment. For example, look at this change to your code where foo()
returns x
:
# config.R
x <- 1
foo <- function() {
x
}
z <- x + 1
and then
source_in_list <- function(path) {
e <- new.env()
source(path, local = e)
return(as.list(e))
}
p <- source_in_list("config.R")
x <- 42 # Set a global variable x
p$foo()
# [1] 1 # It is ignored
p$x <- 123 # Set x in p
p$foo()
# [1] 1 # It is ignored
You probably don't want two copies of everything. But then it's not clear that what you want to do is possible. A list can't act as the environment of a function, so there's no way to make p$x
be the target of references from within foo
.
I'd suggest that instead of returning a list, you just return the local environment you created. Then things will work as you'd expect:
source_to_local <- function(path) {
e <- new.env()
source(path, local = e)
return(e)
}
e <- source_to_local("config.R")
x <- 42 # set a global
e$foo()
[1] 1 # it is ignored
e$x <- 123 # set x in e
e$foo()
[1] 123 # it responds
The main disadvantage of returning the environment is that they don't print the way lists do, but you could probably write a function to print an environment and make everything in it visible.
Pulling all objects in the global environment that have specific attributes
Here is one way to do it
# collect all objects in global environment
all = lapply(ls(), get)
# extract objects with attribute = "bar"
bar = all[lapply(all, attr, "foo") == "bar"]
Iteratively create global environment objects from tibble
As we already returned the object value in a list
, we need only to specify the lambda function i.e. .x
returns the value of the list
element which is a tibble
and extract the column
library(purrr)
list_output <- map(list_df, ~.x$ave_neg_U_ml)
If the intention is to create global objects, deframe
, convert to a list
and then use list2env
library(tibble)
list2env(as.list(deframe(neg_tibble_string)), .GlobalEnv)
Looping through data frames in global environment and passing a function to all to create new list
I've figured out the issue was with my function f1
and mget(ls())
in lapply
. Here's what worked to solve the problem:
A
dfs_list <- Filter(function(x) is(x, "data.frame"), mget(ls()))
B
f1 <- function(df) {
df %>%
dplyr::mutate(dplyr::mutate(row = row_number()) %>%
tidyr::pivot_wider(names_from = row, values_from = -row)
}
C
lst1 <- lapply(dfs_list, f1)
Is there any way to return all objects defined in a function in R?
Is there any way to return all objects defined in a function in R?
Literally, there is1:
as.list(environment())
However, I’d generally recommend against this: be explicit, name all objects that you want to return individually:
list(
foo = foo,
bar = bar,
…
)
1 This will include arguments, since these are just locally defined values. To exclude formal arguments, do this:
values = as.list(environment())
values[setdiff(names(values), names(formals()))]
Related Topics
Efficient Way to Rbind Data.Frames With Different Columns
Multiple Plots in For Loop Ignoring Par
Extracting the Last N Characters from a String in R
R Spreading Multiple Columns With Tidyr
Overlay Normal Curve to Histogram in R
Subscript Letters in Ggplot Axis Label
How to Replace Na With Mean by Group/Subset
How to Merge 2 Vectors Alternating Indexes
Collapsing Rows Where Some Are All Na, Others Are Disjoint With Some Nas
Unique Rows, Considering Two Columns, in R, Without Order
Convert Data.Frame Column Format from Character to Factor
Put Stars on Ggplot Barplots and Boxplots - to Indicate the Level of Significance (P-Value)
Overlay Histogram With Density Curve
Ggplot, Facet, Piechart: Placing Text in the Middle of Pie Chart Slices
How to Extract a Single Column from a Data.Frame as a Data.Frame