[R] looping with paste

Juta Kawalerowicz juta.kawalerowicz at stx.ox.ac.uk
Fri Aug 26 18:18:14 CEST 2011


Dear Sarah and Rolf, 

Thanks for your suggestions, yes I was looking for something that'd execute strings eval(parse) was a solution. It's extremely helpful when you want to do something on variables generated with loops.

Juta
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
From: Rolf Turner [rolf.turner at xtra.co.nz]
Sent: 22 August 2011 23:36
To: Sarah Goslee
Cc: Juta Kawalerowicz; r-help at r-project.org
Subject: Re: [R] looping with paste

As Sarah has said, you probably don't need to use "paste()" at all.  However
if "command" is a text string containing a (syntactically correct) R command
you can execute it via

     eval(parse(text=command))

E.g.:

     command <- "x <- 42"
     eval(parse(text=command))
     x
     [1] 42

I find this to be a useful trick in quite a few contexts.

     cheers,

         Rolf Turner

On 23/08/11 08:43, Sarah Goslee wrote:
> Juta,
>
> On Mon, Aug 22, 2011 at 4:29 PM, Juta Kawalerowicz
> <juta.kawalerowicz at stx.ox.ac.uk>  wrote:
>> Dear list,
>>
>> I have a spacialPolygonDataFrame where variables were unnecessarily imported as factors. So I am trying to unfactor variables from spatialPolygonDataFrame at data with a loop
>>
>>
>> for (i in (1:length(names( spatialPolygonDataFrame)))){
>>
>>
>> command<-paste("spatialPolygonDataFrame$names(spatialPolygonDataFrame at data[",i,"])<-as.character( spatialPolygonDataFrame$names( spatialPolygonDataFrame at data[",i,"])")
>> command<-noquote(command)
>> command
>>
>> }
>>
>>
>> But I keep getting just a printout
> Yeah, you're putting together a string, not actually running any commands.
>
> Does this not work:
>
> for (i in (1:length(names( spatialPolygonDataFrame)))){
>
> spatialPolygonDataFrame$names(spatialPolygonDataFrame at data[i])<-
> as.character( spatialPolygonDataFrame$names(
> spatialPolygonDataFrame at data[i]))
>
> }
>
> Subsetting on a variable should work just fine. I don't see any need for
> paste().
>
> Sarah



More information about the R-help mailing list