Hi, Can someone suggest an efficient way to substitute a vector/matrix which contains 1's and 0's to P's and A's (resp.)? Thanks, Lana
On 8/17/2009 10:22 AM, Lana Schaffer wrote:> Hi, > Can someone suggest an efficient way to substitute a vector/matrix > which contains 1's and 0's to P's and A's (resp.)? > Thanks, > LanaHere is one approach: mymat <- matrix(rbinom(15, 1, .5), ncol=3) mymat [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 0 1 [3,] 1 0 1 [4,] 0 1 0 [5,] 1 1 0 mymat[] <- sapply(mymat, function(x){ifelse(x == 1, 'P', ifelse(x == 0, 'A', NA))}) mymat [,1] [,2] [,3] [1,] "P" "A" "A" [2,] "A" "A" "P" [3,] "P" "A" "P" [4,] "A" "P" "A" [5,] "P" "P" "A"> ______________________________________________ > 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.-- Chuck Cleland, Ph.D. NDRI, Inc. (www.ndri.org) 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894
On 17/08/2009 10:22 AM, Lana Schaffer wrote:> Hi, > Can someone suggest an efficient way to substitute a vector/matrix > which contains 1's and 0's to P's and A's (resp.)?x[x == 1] <- "P" x[x == "0"] <- "A" (I added the quotes around 0 on the second line because the first line changed x to a character vector. This isn't necessary, "0" == 0 comes out TRUE, but I think it is clearer.) Duncan Murdoch
Will this do it:> x <- sample(0:1,10,TRUE) > x[1] 1 0 0 1 0 1 0 0 0 0> ifelse(x == 1, "P", "A")[1] "P" "A" "A" "P" "A" "P" "A" "A" "A" "A">On Mon, Aug 17, 2009 at 10:22 AM, Lana Schaffer<schaffer at scripps.edu> wrote:> Hi, > Can someone suggest an efficient way to substitute a vector/matrix > which contains 1's and 0's to P's and A's (resp.)? > Thanks, > Lana > ______________________________________________ > 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. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?
Hi r-help-bounces at r-project.org napsal dne 17.08.2009 16:22:39:> Hi, > Can someone suggest an efficient way to substitute a vector/matrix > which contains 1's and 0's to P's and A's (resp.)?vec<-sample(0:1, 20, replace=T) vec [1] 1 1 0 1 0 1 0 1 0 0 1 1 0 0 0 0 0 0 1 0 vec<-ifelse(vec==0, "A", "P") vec [1] "P" "P" "A" "P" "A" "P" "A" "P" "A" "A" "P" "P" "A" "A" "A" "A" "A" "A" "P" "A" Regards Petr> Thanks, > Lana > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.