Hi All, I would like to access an object using a sting. # Create example dataset var1 <- c(1, 2, 3) var2 <- c(4, 5, 6) data1 <- data.frame(var1, var2) var3 <- c(7, 8, 9) var4 <- c(10, 11, 12) data2 <- data.frame(var3, var4) save(file = "c:/temp/test.RData", list = c("data1", "data2")) # Define function t_load_dataset <- function(file_path, file_name) { file_location <- file.path(file_path, file_name) print(paste0('Loading ', file_location, " ...")) cat("\n") object_list <- load(file = file_location, envir = .GlobalEnv) print(paste(length(object_list), "dataset(s) loaded from", file_location)) cat("\n") print("The following objects were loaded:") print(object_list) cat("\n") for (i in object_list) { print(paste0("Object '", i, "' in '", file_name, "' contains:")) str(i) names(i) # does not work } } I have only the character vector object_list containing the names of the objects as strings. I would like to access the objects in object_list to be able to print the names of the variables within the object (usuallly a data frame). Is it possible to do this? How is it done? Kind regards Georg
G.Maubach at weinwolf.de
2016-Aug-15 13:40 UTC
[R] Antwort: Accessing an object using a string (SOLVED)
Hi All, I found the function get() which returns an object. My whole function looks like this: -- cut -- #------------------------------------------------------------------------------- # Module : t_load_dataset.R # Author : Georg Maubach # Date : 2016-08-15 # Update : 2016-08-15 # Description : Load dataset and print information on contents # Source System : R 3.3.0 (64 Bit) # Target System : R 3.3.0 (64 Bit) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #--------1---------2---------3---------4---------5---------6---------7---------8 t_module_name = "t_load_dataset" t_version = "2016-08-15" t_status = "released" cat( paste0("\n", t_module_name, " (Version: ", t_version, ", Status: ", t_status, ")", "\n", "\n", "Copyright (C) Georg Maubach 2016 This software comes with ABSOLUTELY NO WARRANTY.", "\n", "\n")) # If do_test is not defined globally define it here locally by un-commenting it # Switch t_do_test to TRUE to run test t_do_test <- FALSE # [ Function Defintion ]-------------------------------------------------------- t_load_dataset <- function(file_path, file_name) { # Loads and RData file with all objects in it and prints information on its # contents # # Args: # file_path (string): # String with path name. # file_name (string): # String with file name. # # Operation: # Loads the RData file with all its objects, stores the objects in the # global environment .GlobalEnv and prints information about the objects. # # Usage: # The function is designed to work only on data frames. # # Returns: # Nothing, but stores loaded objects directly into the global environment. # # Error handling: # None. #----------------------------------------------------------------------------- cat("----------------------- [ t_load_dataset() ] ----------------------\n\n") file_location <- file.path(file_path, file_name) cat(paste0('Loading ', file_location, " ...\n\n")) dataset_list <- load(file = file_location, envir = .GlobalEnv) cat(paste0( length(dataset_list), " dataset(s) loaded:\n")) cat(dataset_list) cat("\n\n") for (dataset in dataset_list) { cat(paste0("Dataset '", dataset, "' contains ", nrow(get(dataset, envir = .GlobalEnv)), " cases in ", ncol(get(dataset, envir = .GlobalEnv)), " variables:\n")) cat(names(get(dataset, envir = .GlobalEnv))) cat("\n\n") } cat("------------------------------ [ Done ] ---------------------------\n\n") } # [ Test Defintion ]------------------------------------------------------------ t_test <- function(do_test = FALSE) { if (do_test == TRUE) { # Example dataset var1 <- c(1, 2, 3) var2 <- c(4, 5, 6) d_data1 <- data.frame(var1, var2) var3 <- c(7, 8, 9) var4 <- c(10, 11, 12) d_data2 <- data.frame(var3, var4) # Save datasets v_file_name <- "test_t_load_dataset.RData" save(file = file.path(getwd(), v_file_name), list = c("d_data1", "d_data2")) # Call function t_load_dataset(file_path = getwd(), file_name = v_file_name) # Cleanup unlink(file.path(getwd(), v_file_name)) } } # [ Test Run ]------------------------------------------------------------------ t_test(do_test = t_do_test) # [ Clean up ]------------------------------------------------------------------ rm("t_module_name", "t_version", "t_status", "t_do_test", "t_test") # EOF -- cut -- I will include it later the toolbox of R function on Sourceforge.net. Kind regards Georg Von: G.Maubach at weinwolf.de An: r-help at r-project.org, Datum: 15.08.2016 10:51 Betreff: [R] Accessing an object using a string Gesendet von: "R-help" <r-help-bounces at r-project.org> Hi All, I would like to access an object using a sting. # Create example dataset var1 <- c(1, 2, 3) var2 <- c(4, 5, 6) data1 <- data.frame(var1, var2) var3 <- c(7, 8, 9) var4 <- c(10, 11, 12) data2 <- data.frame(var3, var4) save(file = "c:/temp/test.RData", list = c("data1", "data2")) # Define function t_load_dataset <- function(file_path, file_name) { file_location <- file.path(file_path, file_name) print(paste0('Loading ', file_location, " ...")) cat("\n") object_list <- load(file = file_location, envir = .GlobalEnv) print(paste(length(object_list), "dataset(s) loaded from", file_location)) cat("\n") print("The following objects were loaded:") print(object_list) cat("\n") for (i in object_list) { print(paste0("Object '", i, "' in '", file_name, "' contains:")) str(i) names(i) # does not work } } I have only the character vector object_list containing the names of the objects as strings. I would like to access the objects in object_list to be able to print the names of the variables within the object (usuallly a data frame). Is it possible to do this? How is it done? Kind regards Georg ______________________________________________ R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Jeff Newmiller
2016-Aug-15 16:41 UTC
[R] Antwort: Accessing an object using a string (SOLVED)
Use of "get" usually means you are doing something wrong in setting up your approach to a problem. That is, if you design your interface to your functions to be overly general, it will become full of surprises later. If in fact the data you are interested in referring to is a column in a data frame, then let the user give your function that data frame as a function argument and use indexing to extract the value from it. Don't design your function to go digging around in the global environment because the user of your function may not be working there. In this case, it would be better for the user to create a dedicated environment and load the RData file into that and use the ls() and str () functions to look through it rather than assume the RData file only contains data frames by using your function. x <- 1:5 dta <- data.frame( x, y = x + 1 ) save.image( "test.RData" ) rm( x ) rm( dta ) en <- new.env() ls() ls( en ) load( "test.RData", envir=en ) ls( en ) str( x ) # removed from working environment str( en$x ) str( en$dta ) -- Sent from my phone. Please excuse my brevity. On August 15, 2016 6:40:58 AM PDT, G.Maubach at weinwolf.de wrote:>Hi All, > >I found the function get() which returns an object. > >My whole function looks like this: > >-- cut -- > >#------------------------------------------------------------------------------- ># Module : t_load_dataset.R ># Author : Georg Maubach ># Date : 2016-08-15 ># Update : 2016-08-15 ># Description : Load dataset and print information on contents ># Source System : R 3.3.0 (64 Bit) ># Target System : R 3.3.0 (64 Bit) ># ># This program is distributed in the hope that it will be useful, ># but WITHOUT ANY WARRANTY; without even the implied warranty of ># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. >#--------1---------2---------3---------4---------5---------6---------7---------8 > >t_module_name = "t_load_dataset" >t_version = "2016-08-15" >t_status = "released" > >cat( > paste0("\n", > t_module_name, " (Version: ", t_version, ", Status: ", t_status, >")", "\n", "\n", > "Copyright (C) Georg Maubach 2016 > >This software comes with ABSOLUTELY NO WARRANTY.", "\n", "\n")) > ># If do_test is not defined globally define it here locally by >un-commenting it ># Switch t_do_test to TRUE to run test >t_do_test <- FALSE > ># [ Function Defintion >]-------------------------------------------------------- >t_load_dataset <- function(file_path, > file_name) { ># Loads and RData file with all objects in it and prints information on > >its > # contents > # > # Args: > # file_path (string): > # String with path name. > # file_name (string): > # String with file name. > # > # Operation: ># Loads the RData file with all its objects, stores the objects in >the > # global environment .GlobalEnv and prints information about the >objects. > # > # Usage: > # The function is designed to work only on data frames. > # > # Returns: > # Nothing, but stores loaded objects directly into the global >environment. > # > # Error handling: > # None. > >#----------------------------------------------------------------------------- > > cat("----------------------- [ t_load_dataset() ] >----------------------\n\n") > > file_location <- file.path(file_path, file_name) > > cat(paste0('Loading ', file_location, " ...\n\n")) > > dataset_list <- load(file = file_location, > envir = .GlobalEnv) > > cat(paste0( > length(dataset_list), > " dataset(s) loaded:\n")) > cat(dataset_list) > cat("\n\n") > > for (dataset in dataset_list) { > cat(paste0("Dataset '", dataset, "' contains ", > nrow(get(dataset, envir = .GlobalEnv)), > " cases in ", > ncol(get(dataset, envir = .GlobalEnv)), > " variables:\n")) > cat(names(get(dataset, envir = .GlobalEnv))) > cat("\n\n") > } > > cat("------------------------------ [ Done ] >---------------------------\n\n") >} > ># [ Test Defintion >]------------------------------------------------------------ >t_test <- function(do_test = FALSE) { > if (do_test == TRUE) { > > # Example dataset > var1 <- c(1, 2, 3) > var2 <- c(4, 5, 6) > d_data1 <- data.frame(var1, var2) > > var3 <- c(7, 8, 9) > var4 <- c(10, 11, 12) > d_data2 <- data.frame(var3, var4) > > # Save datasets > v_file_name <- "test_t_load_dataset.RData" > > save(file = file.path(getwd(), > v_file_name), > list = c("d_data1", "d_data2")) > > # Call function > t_load_dataset(file_path = getwd(), file_name = v_file_name) > > # Cleanup > unlink(file.path(getwd(), v_file_name)) > } >} > ># [ Test Run >]------------------------------------------------------------------ >t_test(do_test = t_do_test) > ># [ Clean up >]------------------------------------------------------------------ >rm("t_module_name", "t_version", "t_status", "t_do_test", "t_test") > ># EOF > >-- cut -- > >I will include it later the toolbox of R function on Sourceforge.net. > >Kind regards > >Georg > > > > >Von: G.Maubach at weinwolf.de >An: r-help at r-project.org, >Datum: 15.08.2016 10:51 >Betreff: [R] Accessing an object using a string >Gesendet von: "R-help" <r-help-bounces at r-project.org> > > > >Hi All, > >I would like to access an object using a sting. > ># Create example dataset >var1 <- c(1, 2, 3) >var2 <- c(4, 5, 6) >data1 <- data.frame(var1, var2) > >var3 <- c(7, 8, 9) >var4 <- c(10, 11, 12) >data2 <- data.frame(var3, var4) > >save(file = "c:/temp/test.RData", list = c("data1", "data2")) > ># Define function >t_load_dataset <- function(file_path, > file_name) { > file_location <- file.path(file_path, file_name) > > print(paste0('Loading ', file_location, " ...")) > cat("\n") > > object_list <- load(file = file_location, > envir = .GlobalEnv) > > print(paste(length(object_list), "dataset(s) loaded from", >file_location)) > cat("\n") > > print("The following objects were loaded:") > print(object_list) > cat("\n") > > for (i in object_list) { > print(paste0("Object '", i, "' in '", file_name, "' contains:")) > str(i) > names(i) # does not work > } >} > >I have only the character vector object_list containing the names of >the >objects as strings. I would like to access the objects in object_list >to >be able to print the names of the variables within the object (usuallly >a >data frame). > >Is it possible to do this? How is it done? > >Kind regards > >Georg > >______________________________________________ >R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide >http://www.R-project.org/posting-guide.html >and provide commented, minimal, self-contained, reproducible code. > >______________________________________________ >R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see >https://stat.ethz.ch/mailman/listinfo/r-help >PLEASE do read the posting guide >http://www.R-project.org/posting-guide.html >and provide commented, minimal, self-contained, reproducible code.
The names function is a primitive, which means that if it does not already do what you want, it is generally not going to be easy to coerce it to do it. However, the names of an object are generally stored as an attribute of that object, which can be accessed using the attr or attributes functions. If you change your code to not use the names function and instead use attr or attributes to access the names then it should work for you. You may also want to consider changing your workflow to have your data objects read into a list rather than global variables, then process using lapply/sapply (this would require a change in how your data is saved from your example, but if you can change that then everything after can be cleaner/simpler/easier/more fool proof/etc.) On Mon, Aug 15, 2016 at 2:49 AM, <G.Maubach at weinwolf.de> wrote:> Hi All, > > I would like to access an object using a sting. > > # Create example dataset > var1 <- c(1, 2, 3) > var2 <- c(4, 5, 6) > data1 <- data.frame(var1, var2) > > var3 <- c(7, 8, 9) > var4 <- c(10, 11, 12) > data2 <- data.frame(var3, var4) > > save(file = "c:/temp/test.RData", list = c("data1", "data2")) > > # Define function > t_load_dataset <- function(file_path, > file_name) { > file_location <- file.path(file_path, file_name) > > print(paste0('Loading ', file_location, " ...")) > cat("\n") > > object_list <- load(file = file_location, > envir = .GlobalEnv) > > print(paste(length(object_list), "dataset(s) loaded from", > file_location)) > cat("\n") > > print("The following objects were loaded:") > print(object_list) > cat("\n") > > for (i in object_list) { > print(paste0("Object '", i, "' in '", file_name, "' contains:")) > str(i) > names(i) # does not work > } > } > > I have only the character vector object_list containing the names of the > objects as strings. I would like to access the objects in object_list to > be able to print the names of the variables within the object (usuallly a > data frame). > > Is it possible to do this? How is it done? > > Kind regards > > Georg > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.-- Gregory (Greg) L. Snow Ph.D. 538280 at gmail.com
'names' is an S3-generic function. E.g., in R-3.3.0: > names.unnamed <- function(x) sprintf("#%0*d", ceiling(log10(length(x))), seq_along(x)) > u <- structure(letters, class="unnamed") > names(u) [1] "#01" "#02" "#03" "#04" "#05" "#06" "#07" [8] "#08" "#09" "#10" "#11" "#12" "#13" "#14" [15] "#15" "#16" "#17" "#18" "#19" "#20" "#21" [22] "#22" "#23" "#24" "#25" "#26" There are a lot of C/C++ based functions that use an internal function to get the names of vectors and they may not use this method, but R code will use it. Bill Dunlap TIBCO Software wdunlap tibco.com On Mon, Aug 15, 2016 at 11:33 AM, Greg Snow <538280 at gmail.com> wrote:> The names function is a primitive, which means that if it does not > already do what you want, it is generally not going to be easy to > coerce it to do it. > > However, the names of an object are generally stored as an attribute > of that object, which can be accessed using the attr or attributes > functions. If you change your code to not use the names function and > instead use attr or attributes to access the names then it should work > for you. > > > You may also want to consider changing your workflow to have your data > objects read into a list rather than global variables, then process > using lapply/sapply (this would require a change in how your data is > saved from your example, but if you can change that then everything > after can be cleaner/simpler/easier/more fool proof/etc.) > > > On Mon, Aug 15, 2016 at 2:49 AM, <G.Maubach at weinwolf.de> wrote: > > Hi All, > > > > I would like to access an object using a sting. > > > > # Create example dataset > > var1 <- c(1, 2, 3) > > var2 <- c(4, 5, 6) > > data1 <- data.frame(var1, var2) > > > > var3 <- c(7, 8, 9) > > var4 <- c(10, 11, 12) > > data2 <- data.frame(var3, var4) > > > > save(file = "c:/temp/test.RData", list = c("data1", "data2")) > > > > # Define function > > t_load_dataset <- function(file_path, > > file_name) { > > file_location <- file.path(file_path, file_name) > > > > print(paste0('Loading ', file_location, " ...")) > > cat("\n") > > > > object_list <- load(file = file_location, > > envir = .GlobalEnv) > > > > print(paste(length(object_list), "dataset(s) loaded from", > > file_location)) > > cat("\n") > > > > print("The following objects were loaded:") > > print(object_list) > > cat("\n") > > > > for (i in object_list) { > > print(paste0("Object '", i, "' in '", file_name, "' contains:")) > > str(i) > > names(i) # does not work > > } > > } > > > > I have only the character vector object_list containing the names of the > > objects as strings. I would like to access the objects in object_list to > > be able to print the names of the variables within the object (usuallly a > > data frame). > > > > Is it possible to do this? How is it done? > > > > Kind regards > > > > Georg > > > > ______________________________________________ > > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > > https://stat.ethz.ch/mailman/listinfo/r-help > > PLEASE do read the posting guide http://www.R-project.org/ > posting-guide.html > > and provide commented, minimal, self-contained, reproducible code. > > > > -- > Gregory (Greg) L. Snow Ph.D. > 538280 at gmail.com > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/ > posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]
G.Maubach at weinwolf.de
2016-Aug-16 06:43 UTC
[R] Antwort: Re: Accessing an object using a string
Hi Greg and all others who replied to my question, many thanks for all your answers and help. Currently I store all my objects in .GlobalEnv = Workspace. I am not yet familiar working with different environments nor did I see that this would be necessary for my analysis. Could you explain why working with different environments would be helpful? You suggested to read variables into lists rather than storing them in global variables. This sounds interesting. Could you provide an example of how to define and use this? Kind regards Georg Von: Greg Snow <538280 at gmail.com> An: G.Maubach at weinwolf.de, Kopie: r-help <r-help at r-project.org> Datum: 15.08.2016 20:33 Betreff: Re: [R] Accessing an object using a string The names function is a primitive, which means that if it does not already do what you want, it is generally not going to be easy to coerce it to do it. However, the names of an object are generally stored as an attribute of that object, which can be accessed using the attr or attributes functions. If you change your code to not use the names function and instead use attr or attributes to access the names then it should work for you. You may also want to consider changing your workflow to have your data objects read into a list rather than global variables, then process using lapply/sapply (this would require a change in how your data is saved from your example, but if you can change that then everything after can be cleaner/simpler/easier/more fool proof/etc.) On Mon, Aug 15, 2016 at 2:49 AM, <G.Maubach at weinwolf.de> wrote:> Hi All, > > I would like to access an object using a sting. > > # Create example dataset > var1 <- c(1, 2, 3) > var2 <- c(4, 5, 6) > data1 <- data.frame(var1, var2) > > var3 <- c(7, 8, 9) > var4 <- c(10, 11, 12) > data2 <- data.frame(var3, var4) > > save(file = "c:/temp/test.RData", list = c("data1", "data2")) > > # Define function > t_load_dataset <- function(file_path, > file_name) { > file_location <- file.path(file_path, file_name) > > print(paste0('Loading ', file_location, " ...")) > cat("\n") > > object_list <- load(file = file_location, > envir = .GlobalEnv) > > print(paste(length(object_list), "dataset(s) loaded from", > file_location)) > cat("\n") > > print("The following objects were loaded:") > print(object_list) > cat("\n") > > for (i in object_list) { > print(paste0("Object '", i, "' in '", file_name, "' contains:")) > str(i) > names(i) # does not work > } > } > > I have only the character vector object_list containing the names of the > objects as strings. I would like to access the objects in object_list to > be able to print the names of the variables within the object (usualllya> data frame). > > Is it possible to do this? How is it done? > > Kind regards > > Georg > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.-- Gregory (Greg) L. Snow Ph.D. 538280 at gmail.com