Skip to content

Instantly share code, notes, and snippets.

@pschwede
Last active July 7, 2016 12:37
Show Gist options
  • Save pschwede/3dee9d2e11d20ade9ce7 to your computer and use it in GitHub Desktop.
Save pschwede/3dee9d2e11d20ade9ce7 to your computer and use it in GitHub Desktop.
R example to show how to access a set of named variables e. g. generated by an iterable in a loop using paste() and assign().
# This is an example to show how to access a set of variables named e. g. by an iterable during an iteration.
#
# BE WARNED: The following coding strategy is not easy to debug!
#
# Some like to generate variables, rather than having just one list of all data sets.
# That way you get an introspectable object for each data set – which particularly eases debugging in RStudio.
# To create variables in a loop or other generative iterations R provides paste(), assign() and get().
# * With paste(), you can concatenate strings. (Use it to compose variable names.)
# * With assign(), you can give variables a value using their name in a string and of course the value you give.
# * With get() you can access such named variables using the sting.
# In that case, you might have tried to access your data like this, or similar:
# get(paste("complicated", "_", bandwidth, sep=""))[get(paste("complicated", "_", bandwidth, "$", "x", sep=""))]
# First off: this is way too much in one step! Secondly using "$" to access content of lists is deprecated.
# I present an alternative way that looks simplier to me. But I am not an expert in R, though.
# keywords: input data loop read-in extract object rstudio rlang r-studio r-lang r-project
####
# First, here is some pre-constructed data without a loop.
complicated_0.1 <- list("x" = c(1,2,3), "y" = c(4,5,6), comment="just some sample data")
complicated_0.2 <- list("x" = c(7,8,9), "y" = c(10,11,12), comment="or some read.table input")
complicated_0.1special <- list("x" = c(13,14,15), "y" = c(16,17,18), comment="just some sample data")
# Alternatively (also do-able in a loop)
assign(paste("complicated_", 0.2, "special"),
list("x" = c(19,20,21), "y" = c(22,23,24), comment="ajlshdah"))
####
# Here comes the iteration:
for (bandwidth in c(0.1, 0.2)) {
name1 = paste("complicated", "_", bandwidth, sep="")
name2 = paste(name1, "special", sep="")
value = "x"
# now print (or plot or whatever you like) (TADAA:)
print(paste(bandwidth, ": ",
get(name1)[[value]], ", ",
get(name2)[[value]], "; ", sep=""))
}
####
# That's all!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment