### code ### x=sample(LETTERS[1:26],100,T) prob=function(y){ count=sum(x==y) total=length(x) count/total } ### end ### How do I quote the letters A,B,C,D ect, in order to make the "prob" function return the weights of the desired Letter? Thanks! -- View this message in context: http://r.789695.n4.nabble.com/how-to-quote-factors-in-a-function-tp3805913p3805913.html Sent from the R help mailing list archive at Nabble.com.
R. Michael Weylandt <michael.weylandt@gmail.com>
2011-Sep-11 23:48 UTC
[R] how to quote "factors" in a function?
You quote them in quotes. "A" Also: bad scoping. Michael Weylandt On Sep 11, 2011, at 6:11 PM, casperyc <casperyc at hotmail.co.uk> wrote:> ### code ### > x=sample(LETTERS[1:26],100,T) > prob=function(y){ > count=sum(x==y) > total=length(x) > count/total > } > ### end ### > > How do I quote the letters A,B,C,D ect, in order to make the "prob" function > return the weights of the desired Letter? > > Thanks! > > -- > View this message in context: http://r.789695.n4.nabble.com/how-to-quote-factors-in-a-function-tp3805913p3805913.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.
Hi casperyc, Try # option 1 x <- sample(LETTERS[1:26], 100, TRUE) prob <- function(y){ count=sum(x==y) total=length(x) count/total } prob('A') prob('B') prob('Z') # option 2 tx <- prop.table(table(x)) tx tx['A'] # option 2.1 foo <- function(x, l = NULL){ tx <- prop.table(table(x)) if(is.null(l)){ r <- tx } else r <- tx[l] r } foo(x) foo(x, 'A') HTH, Jorge On Sun, Sep 11, 2011 at 6:11 PM, casperyc <> wrote:> ### code ### > x=sample(LETTERS[1:26],100,T) > prob=function(y){ > count=sum(x==y) > total=length(x) > count/total > } > ### end ### > > How do I quote the letters A,B,C,D ect, in order to make the "prob" > function > return the weights of the desired Letter? > > Thanks! > > -- > View this message in context: > http://r.789695.n4.nabble.com/how-to-quote-factors-in-a-function-tp3805913p3805913.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]