[R] Antwort: Accessing an object using a string (SOLVED)

Bert Gunter bgunter.4567 at gmail.com
Mon Aug 15 19:46:48 CEST 2016


While I generally agree with Jeff's caution and advice about the use
of get(), I have also often struggled with designing suitable
interfaces for loading and saving files. So I just wanted to add that
the interactive file.choose() function can be very helpful in this
context if you aren't already aware of it.

Cheers,
Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Mon, Aug 15, 2016 at 9:41 AM, Jeff Newmiller
<jdnewmil at dcn.davis.ca.us> wrote:
> 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.
>
> ______________________________________________
> 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.



More information about the R-help mailing list