[R] Working with lists with numerical names

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Fri Feb 24 00:23:32 CET 2006



Christopher Swingley wrote:
> Greetings!
> 
> I'm have a hard time working with some data I imported from a baseball
> database.  Several of the database columns have numbers in them (2B,
> 3B), and when I try to use these vectors from the data frame, I get
> syntax errors, probably because it's interpreting the name as a number:
> 
>  > show(batting2005)
>    playerID yearID stint teamID lgID   G  AB   R   H 2B 3B HR RBI SB CS  BB
>    1   robleos01   2005     1    LAN   NL 110 364  44  99 18  1  5 34  0  8  31
>    2   iguchta01   2005     1    CHA   AL 135 511  74 142 25  6 15 71 15  5  47
>    3   molinya01   2005     1    SLN   NL 114 385  36  97 15  1  8 49  2  3  23
>    . . .
>  > print(batting2005$HR)
>    [1]  5 15  8  3 14  3  6 21  8  7  9 27 12  5 14  8 28  9 22 15  5
>    22  9 10  1
>    . . .
>  > print(batting2005$2B)
>  Error: syntax error in "print(batting2005$2"
> 
>  > SLG<-(H + 2B + 3B * 2 + HR * 3) / AB;
>  Error: syntax error in "SLG<-(H + 2B"      # batting2005 is attached
> 
>  > SLG<-(H + "2B" + "3B" * 2 + HR * 3) / AB;
>  Error in H + "2B" : non-numeric argument to binary operator
> 
> Is there a way to "escape" the '2B' somehow or encapsulate it so that R
> knows I'm talking about that particular numeric vector?
> 
> Thanks,
> 
> Chris

Hi, Chris,

 > x <- data.frame(1:5, 6:10)
 > names(x) <- c("R", "2B")
 > x
   R 2B
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
 > x$"2B"
[1]  6  7  8  9 10
 > with(x, R + `2B`)
[1]  7  9 11 13 15

HTH,

--sundar




More information about the R-help mailing list