How to call an object with the character variable of the same name
I think you want get
.
data <- get(i)
That said, once you start using get
(and its counterpart, assign
), you usually end up with horrible unreadable code.
For batch analyses like yours, it is often better to read all your data into a list of data frames, then make liberal use of lapply
. Something like:
data_files <- list.files()
all_vars <- lapply(data_files, function(file)
{
vars_loaded <- load(file)
mget(vars_loaded, parent.frame())
})
mget
is the version of get
that retrieves multiple variables at once. Here it is used to retrieve all the things that were loaded by the call to load.
Now you have a list of lists: the top level list is related to the file, lower level lists contain the variables loaded from that file.
Access multiple object based on the name of a string
I can not test it but I think:
read.table(get(paste(data,"scores_dir",sep="_")),header=T))
would do it
How to assign a variable values stored in a vector to a series of variable names stored in a character vector in R?
assign
is not vectorized, so you can use Map
here specifying the environment.
Map(function(x, y) assign(x, y, envir = .GlobalEnv), my_variables, my_values)
A
#[1] 1
B
#[1] 2
C
#[1] 3
However, it is not a good practice to have such variables in the global environment.
Use a named vector :
name_vec <- setNames(my_values, my_variables)
name_vec
#A B C
#1 2 3
Or named list as.list(name_vec)
.
How to set a specific attribute of an object if the object name is in a variable?
You can use a function to apply the attributes and the assign function to apply them:
add_dummy <- function(obj, name, attribute){
attr(obj, name) <- attribute
return(obj)
}
assign(var, add_dummy(get(var), "attr_name", list(dummy = 123)))
Related Topics
Summarizing Multiple Columns With Dplyr
Side-By-Side Plots With Ggplot2
How to Get a Contingency Table
How to Disable Scientific Notation
How to Install an R Package from Source
Convert Data from Long Format to Wide Format With Multiple Measure Columns
Extract the Maximum Value Within Each Group in a Dataframe
Group by Multiple Columns and Sum Other Multiple Columns
How to Sort a Character Vector Where Elements Contain Letters and Numbers
How to Call an Object With the Character Variable of the Same Name
Count Number of Rows in a Data Frame in R Based on Group
Strptime, As.Posixct and As.Date Return Unexpected Na
Ggplot2 - Annotate Outside of Plot
Opposite of %In%: Exclude Rows With Values Specified in a Vector