[R] evaluating a vector of characters

Marc Schwartz marc_schwartz at comcast.net
Mon Jan 7 20:04:24 CET 2008


Henrique Dallazuanna wrote:
> Try: sapply(paste("Data$x", 1:3, sep=""),
> function(x)eval(parse(text=x)))
> 
> On 07/01/2008, Gregory Gentlemen <gregory_gentlemen at yahoo.ca> wrote:
>> Dear R users,
>> 
>> I'd like to evaluate a vector of characters. For example, say I
>> have a data frame called Data including the field names x1, x2, x3,
>> and I'd like to a list out of paste("Data$x", 1:3, sep=""). How can
>> I get list to evaluate paste("Data$x", 1:3, sep="") as an R object
>> rather than a string?
>> 
>> Thanks in advance for you assistance. Gregory

 > fortune(106)

If the answer is parse() you should usually rethink the question.
    -- Thomas Lumley
       R-help (February 2005)

:-)

Try this:

 > Data <- data.frame(x1 = 1:3, x2 = letters[1:3], x3 = 4:6, x4 = 8:10)

 > Data
   x1 x2 x3 x4
1  1  a  4  8
2  2  b  5  9
3  3  c  6 10


Since the only part that is varying is the column names:

Data[, paste("x", 1:3, sep="")]
   x1 x2 x3
1  1  a  4
2  2  b  5
3  3  c  6

or

 > subset(Data, select = paste("x", 1:3, sep=""))
   x1 x2 x3
1  1  a  4
2  2  b  5
3  3  c  6


See ?subset.  Alternatively, see ?get for other ways of returning R 
objects using character vectors.

For example, a bit more convoluted, but you could also do:

MyDF <- "Data"
Cols <- paste("x", 1:3, sep="")

 > get(MyDF)[, Cols]
   x1 x2 x3
1  1  a  4
2  2  b  5
3  3  c  6

This gives you more flexibility in having both the name of the data 
frame and the desired subset of columns within the data frame as 
character vectors.

HTH,

Marc Schwartz




More information about the R-help mailing list