Dear list, I need help, since I can not come up with an easy solution to convert this vector test <- c('p','p','t','t','t') to [1] NA NA 1 2 3 which means the occurences of 't' should be summed up at the corresponding positions. The solution should also be able to handle the following scenarios: test2 <- c('t','t','t') [1] 1 2 3 test3 <- c('p','p') [1] NA NA test <- c('p','p','t','t','t','p','k','t') [1] NA NA 1 2 3 NA NA 4 I would really appreciate an easy solution! Thanks, Stefan
You will get 0s instead of NAs, but this may suffice: cumsum(test == 't') b On Nov 5, 2009, at 11:30 AM, Stefan Uhmann wrote:> Dear list, > > I need help, since I can not come up with an easy solution to convert > this vector > > test <- c('p','p','t','t','t') > > to > > [1] NA NA 1 2 3 > > which means the occurences of 't' should be summed up at the > corresponding positions. The solution should also be able to handle > the > following scenarios: > > test2 <- c('t','t','t') > > [1] 1 2 3 > > test3 <- c('p','p') > > [1] NA NA > > test <- c('p','p','t','t','t','p','k','t') > > [1] NA NA 1 2 3 NA NA 4 > > > I would really appreciate an easy solution! > > Thanks, > Stefan > > ______________________________________________ > 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.
one approach is the following: test <- c('p','p','t','t','t','p','k','t') v <- cumsum(ind <- test == 't') v[!ind] <- NA v I hope it helps. Best, Dimitris Stefan Uhmann wrote:> Dear list, > > I need help, since I can not come up with an easy solution to convert > this vector > > test <- c('p','p','t','t','t') > > to > > [1] NA NA 1 2 3 > > which means the occurences of 't' should be summed up at the > corresponding positions. The solution should also be able to handle the > following scenarios: > > test2 <- c('t','t','t') > > [1] 1 2 3 > > test3 <- c('p','p') > > [1] NA NA > > test <- c('p','p','t','t','t','p','k','t') > > [1] NA NA 1 2 3 NA NA 4 > > > I would really appreciate an easy solution! > > Thanks, > Stefan > > ______________________________________________ > 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. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014