How to Call an Object With the Character Variable of the Same Name

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



Leave a reply



Submit