[R] ask for help

Bart Kastermans kasterma at kasterma.net
Thu Aug 7 17:28:33 CEST 2014


For readability I like:

> b <- c(0,a[-length(a)])
> which(a != b & a == 0)
[1]  4 12 18
> which(a != b & a == 1)
[1]  1  6 16 23


On 07 Aug 2014, at 17:23, William Dunlap <wdunlap at tibco.com> wrote:

> My solution may be a bit clearer if you define the function isFirstInRun
> isFirstInRun <- function(x) {
>   if (length(x) == 0) {
>      logical(0)
>   } else {
>      c(TRUE, x[-1] != x[-length(x)])
>   }
> }
> 
> Then that solution is equivalent to
>   which(isFirstInRun(a) & a==1)
> 
> If 'a' contains NA's then you have to decide how to deal with them.
> 
> (The call to 'which' is not needed if you are going to be using the
> result as a subscript.)
> 
> You may also want isLastInRun
> isLastInRun <- function(x) {
>   if (length(x) == 0) {
>      logical(0)
>   } else {
>      c(x[-1] != x[-length(x)], TRUE)
>   }
> }
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
> 
> 
> On Thu, Aug 7, 2014 at 7:36 AM, William Dunlap <wdunlap at tibco.com> wrote:
>>> a<-c(1,1,1,0,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1)
>>> which( a==1 & c(TRUE, a[-length(a)]!=1) )
>> [1]  1  6 16 23
>>> which( a==0 & c(TRUE, a[-length(a)]!=0) )
>> [1]  4 12 18
>> 
>> Bill Dunlap
>> TIBCO Software
>> wdunlap tibco.com
>> 
>> 
>> On Wed, Aug 6, 2014 at 7:12 PM, Johnnycz <johnnycz at yeah.net> wrote:
>>> Hello,everybody,
>>>         I have a sequence,like a<-c(1,1,1,0,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1),how to get the position of each first 1 and 0, that's to say, how to get b<-c(1,6,16,23) for first 1 and d<-c(4,12,18) for first 0.
>>>        Many thanks!
>>> Johnny
>>>        [[alternative HTML version deleted]]
>>> 
>>> ______________________________________________
>>> 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.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list