[R] Extracting variables with a given prefix in the parent environment
Duncan Murdoch
murdoch at stats.uwo.ca
Mon Oct 20 12:31:32 CEST 2008
On 20/10/2008 2:06 AM, erwann rogard wrote:
> hi,
>
> get.vars.name.prefix<-function(prefix){
> result<-list()
> len<-nchar(prefix)
> var.names<-ls(name=1,pattern=prefix) #name=1 probably wrong option
> print(var.names)
> for(i in 1:length(var.names)){
> name<-var.names[i]
> field<-substr(name,len+1,nchar(name))
> result[[field]]<-get(name)
> }
> result
> }
>
> for example
> x.1<-1
> x.2<-2
> get.vars.name.prefix("x.") should return 1,2
>
> this does not work if i call if from within another function:
>
> g<-function(){
> x.1<-1
> x.2<-2
> get.vars.name.prefix("x.") # should return 1,2, nothing else
> }
>
> i would like the environment specified within ls(...) to be that of the body
> of the function that calls get.vars.name.prefix. apparently name=1 is
> probably not the right option.
Use ls(name=parent.frame(), pattern=...)
And be careful about the pattern: it's a regular expression, so you
would need to start with a caret "^" to guarantee that it occurs at the
start of the name.
Duncan Murdoch
More information about the R-help
mailing list