[R] How to use a variable after $ ($x) for subscripting a list, How to source from a character object (source(x))
drflxms
drflxms at googlemail.com
Tue Sep 13 10:11:43 CEST 2011
Dear R colleagues,
as result of a function a huge list is generated. From this result list
I'd like to extract information.
Think of the list i.e. as an object named "listResult" with the
following form:
[[a]]
[1] [2] [3] [4] [5]
[[b]]
[1] [2] [3] [4] [5]
[[c]]
[1] [2] [3] [4] [5]
where levels=c(a,b,c)
I'd like to extract a data.frame like
a [2]
b [2]
c [2]
What I tried, is a function like this:
library(foreach)
loopExtract <- function(input) {
foreach(i=1:length(levels)) %do% {listResult[[i]]$input}
...
where the name of the variable [2] is meant to be the input.
Unfortunately it turned out, that the "input"-variable after the $ is
not substituted as expected. Subscripting the list with a variable after
the $ seems not possible.
The only workaround I found for that is a function like
loopExtract <- function(input) {
codetemplate <- as.character("result <- foreach(i=1:length(levels)) %do%
{listResult[[i]]$input)}")
require(stringr)
write(str_replace_all(codetemplate, "input", input), file="tmp.r")
source("tmp.r")
return(result)
}
in other words I stored a template of the desired code as characters in
an object, substituted the "input" string in that character object,
wrote the result to a file and sourced the code of that file.
I stored the result in a file cause the expression source(codetemplate)
did not work. From the documentation I learned, that one can only source
"connections". And there seems no chance to establish a connection to an
object. (Probably no one else, except me, has such a strange idea.)
Well, it works that way, but even though I am not a real programmer, I
realize how dirty this solution is. There must be a much simpler and
elegant way.
To sum it all up, my problem can be reduced to the following two questions
(1) How to subscript a list with a variable after $
(2) How to source from an object containing a code template
or (probably the most promising) (3) How to avoid both ;)
Unfortunately I am not experienced enough to find the solution. Please help!
Greetings from sunny Munich, Felix
More information about the R-help
mailing list