You can use a vector with names
letterGradeToNumber <- c(F=0,D=1,C=2,B=3,A=4)
letterGradeToNumber[c("B", "A")]
B A
3 4
mean(letterGradeToNumber[c("B","A")])
[1] 3.5
or match()
letterGrade <- c("F","D","C","B","A")
numericGrade <- c(0, 1, 2, 3, 4)
numericGrade[match(c("B","A"), letterGrade)]
[1] 3 4
Wrap it up in a function or make a class out of it
and you won't have to remember the details:
> setClass("Grade",representation("integer"))
> setAs("character", "Grade",
function(object)new("Grade",as.integer(c(F=0,D=1,C=2,B=3,A=4)[object])))
> setMethod("show", "Grade",
function(object)show(c("F","D","C","B","A")[object+1]))
> z<-new("Grade", c("D","B","B"))
> mean(z)
[1] 2.333333
> sum(z>1)
[1] 2
> z
[1] "D" "B" "B"
(Although you need to do more to get the right labels on table(z).)
Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com
> -----Original Message-----
> From: s-news-owner@lists.biostat.wustl.edu
> [mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of
> Stuart Luppescu
> Sent: Monday, March 09, 2009 1:38 PM
> To: s-news@lists.biostat.wustl.edu
> Subject: [S] Translating characters
>
> Hello, I have a little problem that should be very easy. Actually, it
> works at the atomic level, but not on vectors.
>
> I want to translate course grades, c("F", "D", "C", "B", "A") to their
> numerical equivalents: c(0, 1, 2, 3, 4). This code works:
>
> > marks <- c("F", "D", "C", "B", "A")
> > foo <- "B"
> > which(marks==foo) - 1
> [1] 3
>
> But when I try to translate a vector of marks to a vector of
> points, it
> fails:
>
> > final.points <- which(marks == testing$final.mark)
> > final.points
> [1] 4 9 16 31 33 38 49 53 56 57 68 69 73 90
> 97 101 106 113
> [19] 116 126 128 131 137 141 146 151 154 156 157 159 160 164
> 171 185 191 198
> [37] 200 206 207 208 231 243 251 252 253 257 261 267 272 277
> 279 282 286 287
>
> If someone could explain this to me I'd be very appreciative.
>
> --
> Stuart Luppescu -=- slu .at. ccsr.uchicago.edu
> University of Chicago -=- CCSR
> 才文と智奈美の父 -=- Kernel 2.6.25-gentoo-r7
> Xander: Well, I guess that makes it official.
> Everybody's paired off. Vampires get dates. Hell,
> even the school librarian sees more action than
> me.
>
>
>
>
>
> --------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu. To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message: unsubscribe s-news
>
|