Re: [R] Can I use "mcnemar.test" for 3*3 tables (or is there a bug in the command?)

2020-08-31 Thread peter dalgaard



> On 30 Aug 2020, at 20:11 , Kyungmin Ko  wrote:
> 
>> 2) The second one is to produce a 3 by 3 table, with the rows indicating
>> what the kids answered to setting 1 of the experiment, and the columns
>> indicating the kids answers to setting 2.
>> Now the question is:
>> was there marginal homogenity? if not, then that is an indicator that the
>> general response to the experimental settings was different for the kids.
> 
>> 1) can I use "mcnemar.test" for 3*3 (or more) tables ?
> As Peter Dalgaard and jchavez12 (on Nabble) pointed out,

Um, that was on July 19, 2009.

> "mcnemar.test" does McNemar-Bowker test (Bowker's test) which tests
> symmetry, not marginal homogeneity.
> Marginal homogeneity and symmetry are equivalent in 2x2 matrices but
> not for larger tables.
> I also was confused because many resources (for example Wikipedia
> accessed 2020-08-30) introduce McNemar's test as a test of marginal
> homogeneity (which it is only for 2x2 matrices).
> The R Reference Manual entry for mcnemar.test states that it tests for 
> symmetry.
> The code for mcnemar.test is also consistent with the McNemar-Bowker
> test for symmetry.
> 
>> Is there a bug in the command?
> Since the function does what the manual states it does, I would not
> call this a bug.
> Although, I would like it if the result of mcnemar.test would print
> "McNemar's Chi-squared test of symmetry" rather than just "McNemar's
> Chi-squared test."
> 
>> Is the one necessarily better then the other? (for example for
>> sparser matrices ?)
> mcnemar.test often fails for sparse matrices, because symmetric zeros
> produce a NaN due to division by zero in the following line of
> mcnemar.test code:
> STATISTIC <- sum(y[upper.tri(x)]^2/x[upper.tri(x)])
> The McNemar-Bowker test uses Chi-squared approximation, which would
> not be good for small counts (and sparse matrices).
> mcnemar.test does not perform continuity correction for matrices
> larger than 2x2.
> Is there an exact test for symmetry of matrices larger than 2x2?
> I could not find one.

The exact test for the 2x2 case is isomorphic to a binomial test of the two 
off-diagonal elements (conditioning on the sum).

The natural way of constructing a test for the k x k case would be based on the 
Cartesian product of k(k-1)/2 binomials with p=.5, (one for each 
i,j-combination). This shouldn't be too hard if k is small, but of course it 
explodes combinatorially as k increases.

-pd

> 
>> Is there a bug in the command?
> I would not call this a bug.
> This behavior of giving "NA" due to a division by zero seems to be
> consistent across statistical tests in R.
> For example chisq.test(matrix(c(0, 0, 1, 2), nrow = 2) gives NA.
> 
>> So which one is "right" ?
> You have the option of the McNemar-Bowker test for symmetry
> (mcnemar.test), and Stuart-Maxwell test (mh_test).
> As an "indicator that the general response to the experimental
> settings was different for the kids,"
> I would think that if marginal homogeneity is rejected, the two tests
> are not equivalent.
> I would run mh_test with distribution = "exact" .
> The relationship between symmetry and equivalence of two tests is not
> as clear to me.
> I suppose if the two experimental settings are equivalent and the
> distribution of random error for each test are also the same the
> resulting matrix would be symmetric?
> 
> R 4.0.2 . coin 1.3.1 .
> 
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd@cbs.dk  Priv: pda...@gmail.com

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] Connection to Oracle DB failing from R

2020-08-31 Thread Christofer Bogaso
Hi,

The Java version below. Let me know if any other information is
required. Thanks,

java -version
java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)


On Mon, Aug 31, 2020 at 8:21 PM William Dunlap  wrote:
>
> Which version of java do you have installed?  Oracle's web site says
> ojdbc5.jar is for Java 1.5 and ojdbc6.jar is for more recent versions.
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
> On Mon, Aug 31, 2020 at 3:56 AM Christofer Bogaso
>  wrote:
> >
> > Hi,
> >
> > I am trying to establish a connection to a Oracle DB from R and used below
> > code which is failing every time I try -
> >
> > > library(RJDBC)
> > Loading required package: DBI
> > > jdbcDriver =JDBC("oracle.jdbc.OracleDriver",classPath="ojdbc5.jar")
> >
> >  *** caught segfault ***
> > address 0x854961, cause 'memory not mapped'
> >
> > Traceback:
> >  1: .jinit(classPath)
> >  2: JDBC("oracle.jdbc.OracleDriver", classPath = "ojdbc5.jar")
> >
> > Possible actions:
> > 1: abort (with core dump, if enabled)
> > 2: normal R exit
> > 3: exit R without saving workspace
> > 4: exit R saving workspace
> > Selection:
> >
> >
> > Below is my session info -
> >
> > > sessionInfo()
> > R version 4.0.2 (2020-06-22)
> > Platform: x86_64-apple-darwin17.0 (64-bit)
> > Running under: macOS Catalina 10.15.6
> >
> > Matrix products: default
> > BLAS:
> >  /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
> > LAPACK:
> > /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
> >
> > locale:
> > [1] C/UTF-8/C/C/C/C
> >
> > attached base packages:
> > [1] stats graphics  grDevices utils datasets  methods   base
> >
> > other attached packages:
> > [1] RJDBC_0.2-8  DBI_1.1.0rJava_0.9-13
> >
> > loaded via a namespace (and not attached):
> > [1] compiler_4.0.2
> >
> > I downloaded the JAR file from
> > https://www.oracle.com/database/technologies/jdbcdriver-ucp-downloads.html
> >
> > Can you please help me to understand why it is failing?
> >
> > [[alternative HTML version deleted]]
> >
> > __
> > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > 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@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] Connection to Oracle DB failing from R

2020-08-31 Thread William Dunlap via R-help
Which version of java do you have installed?  Oracle's web site says
ojdbc5.jar is for Java 1.5 and ojdbc6.jar is for more recent versions.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Mon, Aug 31, 2020 at 3:56 AM Christofer Bogaso
 wrote:
>
> Hi,
>
> I am trying to establish a connection to a Oracle DB from R and used below
> code which is failing every time I try -
>
> > library(RJDBC)
> Loading required package: DBI
> > jdbcDriver =JDBC("oracle.jdbc.OracleDriver",classPath="ojdbc5.jar")
>
>  *** caught segfault ***
> address 0x854961, cause 'memory not mapped'
>
> Traceback:
>  1: .jinit(classPath)
>  2: JDBC("oracle.jdbc.OracleDriver", classPath = "ojdbc5.jar")
>
> Possible actions:
> 1: abort (with core dump, if enabled)
> 2: normal R exit
> 3: exit R without saving workspace
> 4: exit R saving workspace
> Selection:
>
>
> Below is my session info -
>
> > sessionInfo()
> R version 4.0.2 (2020-06-22)
> Platform: x86_64-apple-darwin17.0 (64-bit)
> Running under: macOS Catalina 10.15.6
>
> Matrix products: default
> BLAS:
>  /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
> LAPACK:
> /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
>
> locale:
> [1] C/UTF-8/C/C/C/C
>
> attached base packages:
> [1] stats graphics  grDevices utils datasets  methods   base
>
> other attached packages:
> [1] RJDBC_0.2-8  DBI_1.1.0rJava_0.9-13
>
> loaded via a namespace (and not attached):
> [1] compiler_4.0.2
>
> I downloaded the JAR file from
> https://www.oracle.com/database/technologies/jdbcdriver-ucp-downloads.html
>
> Can you please help me to understand why it is failing?
>
> [[alternative HTML version deleted]]
>
> __
> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] Connection to Oracle DB failing from R

2020-08-31 Thread Marc Schwartz via R-help
> On Aug 31, 2020, at 6:55 AM, Christofer Bogaso  
> wrote:
> 
> Hi,
> 
> I am trying to establish a connection to a Oracle DB from R and used below
> code which is failing every time I try -
> 
>> library(RJDBC)
> Loading required package: DBI
>> jdbcDriver =JDBC("oracle.jdbc.OracleDriver",classPath="ojdbc5.jar")
> 
> *** caught segfault ***
> address 0x854961, cause 'memory not mapped'
> 
> Traceback:
> 1: .jinit(classPath)
> 2: JDBC("oracle.jdbc.OracleDriver", classPath = "ojdbc5.jar")
> 
> Possible actions:
> 1: abort (with core dump, if enabled)
> 2: normal R exit
> 3: exit R without saving workspace
> 4: exit R saving workspace
> Selection:
> 
> 
> Below is my session info -
> 
>> sessionInfo()
> R version 4.0.2 (2020-06-22)
> Platform: x86_64-apple-darwin17.0 (64-bit)
> Running under: macOS Catalina 10.15.6
> 
> Matrix products: default
> BLAS:
> /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
> LAPACK:
> /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
> 
> locale:
> [1] C/UTF-8/C/C/C/C
> 
> attached base packages:
> [1] stats graphics  grDevices utils datasets  methods   base
> 
> other attached packages:
> [1] RJDBC_0.2-8  DBI_1.1.0rJava_0.9-13
> 
> loaded via a namespace (and not attached):
> [1] compiler_4.0.2
> 
> I downloaded the JAR file from
> https://www.oracle.com/database/technologies/jdbcdriver-ucp-downloads.html
> 
> Can you please help me to understand why it is failing?


Hi,

I am copying Simon here, as he is the package author/maintainer for RJDBC.

Typically, segfault's can indicate some kind of version mismatch in the 
components that have been installed.

Since there are multiple pieces to this installation, between the packages and 
the underlying Java installation on your Mac, I would defer to Simon's more 
intimate knowledge here.

In searching for related issues, I noted some other posts on multiple OSs, and 
some issues raised on Simon's Github repo for the package.

Also, I am torn between suggesting that this be re-posted to r-sig-db, which is 
specific to R and database interfaces, and r-sig-mac, which is specific to R on 
macOS. 

However, I will defer to Simon on how he might prefer to handle follow up 
discussion on your issue.

Regards,

Marc Schwartz

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] plot factors with dots in R

2020-08-31 Thread Luigi Marongiu
Thank you, all solutions work!

On Fri, Aug 28, 2020 at 9:02 AM Deepayan Sarkar
 wrote:
>
> On Thu, Aug 27, 2020 at 5:46 PM Luigi Marongiu  
> wrote:
> >
> > Hello,
> > I have a dataframe as follows:
> > ```
> > x = c("0 pmol", "10 pmol", "100 pmol", "1000 pmol")
> > y = c(0.9306, 1.8906, 2.2396, 2.7917)
> > df = data.frame(x, y)
> >
> > > str(df)
> > 'data.frame': 4 obs. of  2 variables:
> >  $ x: chr  "0 pmol" "10 pmol" "100 pmol" "1000 pmol"
> >  $ y: num  0.931 1.891 2.24 2.792
> > ```
> > I would like to visualize the data with the classic dots (pch=16) but:
>
> Perhaps this is a good starting point:
>
> with(df, dotchart(y, labels = x, pch = 16))
>
> -Deepayan
>
> > ```
> > > plot(df$y ~ df$x)
> > Error in plot.window(...) : need finite 'xlim' values
> > In addition: Warning messages:
> > 1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
> > 2: In min(x) : no non-missing arguments to min; returning Inf
> > 3: In max(x) : no non-missing arguments to max; returning -Inf
> > ```
> > which is right because x is not numeric, so I took the factor:
> > ```
> > plot(df$y ~ factor(df$x)) # gives bars instead of dots
> > plot(df$y ~ factor(df$x), pch = 16) # this also
> > ```
> > I tried to convert directly the dataframe:
> > ```
> > df$x = lapply(df$x, factor)
> > > str(df)
> > 'data.frame': 4 obs. of  2 variables:
> >  $ x:List of 4
> >   ..$ : Factor w/ 1 level "0 pmol": 1
> >   ..$ : Factor w/ 1 level "10 pmol": 1
> >   ..$ : Factor w/ 1 level "100 pmol": 1
> >   ..$ : Factor w/ 1 level "1000 pmol": 1
> >  $ y: num  0.931 1.891 2.24 2.792
> >
> > > plot(r$y ~ r$x, pch = 16)
> > Error in plot.window(...) : need finite 'xlim' values
> > In addition: Warning messages:
> > 1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
> > 2: In min(x) : no non-missing arguments to min; returning Inf
> > 3: In max(x) : no non-missing arguments to max; returning -Inf
> > ```
> > If I try to pass the number of levels:
> > ```
> > plot(df$y ~ factor(df$x, 1:4), pch = 16) # this draw a boxplot with
> > all data on level 1
> >
> > > df$x = lapply(df$x, factor(1:4))
> > Error in match.fun(FUN) :
> >   'factor(1:4)' is not a function, character or symbol
> > ```
> >
> > Since the transformation has given only one level (1), my questions are:
> > How do I tell R to use a dot instead of a line?
> > What is the correct way of setting factors?
> >
> >
> > --
> > Best regards,
> > Luigi
> >
> > __
> > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > 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.



-- 
Best regards,
Luigi

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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] Problem running stan interactively

2020-08-31 Thread Tobias Fellinger
Hi,


I try to run a stan model in R 4.0.2 and the session crashes if I run the code 
interactively (sourcing from an interactive session or from Rstudio) but runs 
fine if run with Rscript or R -e 'source("rstan_test.R")' . I don't really know 
where to begin to debug this.

I'm not sure if this is due to the setup on my machine or if this is a bug in 
either the packaging on Debian, the rstan package or R itself, so I'm posting 
it here in the most general mailinglist.


For now just running the model in a non-interactive session is a workaround. R 
and stan code and sessionInfo below.


All the best and thanks in advance, Tobias


 rstan_test.R 
library(rstan)


schools_dat <- list(J = 8,

y = c(28, 8, -3, 7, -1, 1, 18, 12),

sigma = c(15, 10, 16, 11, 9, 11, 10, 18))


fit <- stan(file = 'schools.stan', data = schools_dat)


message("done")




 schools.stan 

// saved as schools.stan

data {

int J; // number of schools

real y[J]; // estimated treatment effects

real sigma[J]; // standard error of effect estimates

}

parameters {

real mu; // population treatment effect

real tau; // standard deviation in treatment effects

vector[J] eta; // unscaled deviation from mu by school

}

transformed parameters {

vector[J] theta = mu + tau * eta; // school treatment effects

}

model {

target += normal_lpdf(eta | 0, 1); // prior log-density

target += normal_lpdf(y | theta, sigma); // log-likelihood

}




 output of sessionInfo 

$ R -e 'library(rstan); sessionInfo()'


R version 4.0.2 (2020-06-22) -- "Taking Off Again"

Copyright (C) 2020 The R Foundation for Statistical Computing

Platform: x86_64-pc-linux-gnu (64-bit)


R is free software and comes with ABSOLUTELY NO WARRANTY.

You are welcome to redistribute it under certain conditions.

Type 'license()' or 'licence()' for distribution details.


Natural language support but running in an English locale


R is a collaborative project with many contributors.

Type 'contributors()' for more information and

'citation()' on how to cite R or R packages in publications.


Type 'demo()' for some demos, 'help()' for on-line help, or

'help.start()' for an HTML browser interface to help.

Type 'q()' to quit R.


> library(rstan); sessionInfo()

Loading required package: StanHeaders

Loading required package: ggplot2

rstan (Version 2.21.2, GitRev: 2e1f913d3ca3)

For execution on a local, multicore CPU with excess RAM we recommend calling

options(mc.cores = parallel::detectCores()).

To avoid recompilation of unchanged Stan programs, we recommend calling

rstan_options(auto_write = TRUE)

R version 4.0.2 (2020-06-22)

Platform: x86_64-pc-linux-gnu (64-bit)

Running under: Debian GNU/Linux 10 (buster)


Matrix products: default

BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3

LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.3.5.so


locale:

[1] LC_CTYPE=en_US.utf8 LC_NUMERIC=C

[3] LC_TIME=en_DK.UTF-8 LC_COLLATE=en_US.utf8

[5] LC_MONETARY=en_DK.UTF-8 LC_MESSAGES=en_US.utf8

[7] LC_PAPER=en_DK.UTF-8 LC_NAME=C

[9] LC_ADDRESS=C LC_TELEPHONE=C

[11] LC_MEASUREMENT=en_DK.UTF-8 LC_IDENTIFICATION=C


attached base packages:

[1] stats graphics grDevices utils datasets methods base


other attached packages:

[1] rstan_2.21.2 ggplot2_3.3.2 StanHeaders_2.21.0-6


loaded via a namespace (and not attached):

[1] Rcpp_1.0.5 pillar_1.4.6 compiler_4.0.2 prettyunits_1.1.1

[5] tools_4.0.2 pkgbuild_1.1.0 jsonlite_1.7.0 lifecycle_0.2.0

[9] tibble_3.0.3 gtable_0.3.0 pkgconfig_2.0.3 rlang_0.4.7

[13] cli_2.0.2 parallel_4.0.2 curl_4.3 loo_2.3.1

[17] gridExtra_2.3 withr_2.2.0 dplyr_1.0.2 generics_0.0.2

[21] vctrs_0.3.4 stats4_4.0.2 grid_4.0.2 tidyselect_1.1.0

[25] glue_1.4.2 inline_0.3.15 R6_2.4.1 processx_3.4.3

[29] fansi_0.4.1 callr_3.4.3 purrr_0.3.4 magrittr_1.5

[33] codetools_0.2-16 scales_1.1.1 ps_1.3.4 ellipsis_0.3.1

[37] matrixStats_0.56.0 assertthat_0.2.1 colorspace_1.4-1 V8_3.2.0

[41] RcppParallel_5.0.2 munsell_0.5.0 crayon_1.3.4

>

>



[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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] Connection to Oracle DB failing from R

2020-08-31 Thread Christofer Bogaso
Hi,

I am trying to establish a connection to a Oracle DB from R and used below
code which is failing every time I try -

> library(RJDBC)
Loading required package: DBI
> jdbcDriver =JDBC("oracle.jdbc.OracleDriver",classPath="ojdbc5.jar")

 *** caught segfault ***
address 0x854961, cause 'memory not mapped'

Traceback:
 1: .jinit(classPath)
 2: JDBC("oracle.jdbc.OracleDriver", classPath = "ojdbc5.jar")

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection:


Below is my session info -

> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6

Matrix products: default
BLAS:
 /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK:
/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] stats graphics  grDevices utils datasets  methods   base

other attached packages:
[1] RJDBC_0.2-8  DBI_1.1.0rJava_0.9-13

loaded via a namespace (and not attached):
[1] compiler_4.0.2

I downloaded the JAR file from
https://www.oracle.com/database/technologies/jdbcdriver-ucp-downloads.html

Can you please help me to understand why it is failing?

[[alternative HTML version deleted]]

__
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.


Re: [R] how to create a sequence to consecutive values

2020-08-31 Thread Stefano Sofia
Thank you both of you. I am studying these solutions.

Stefano

 (oo)
--oOO--( )--OOo
Stefano Sofia PhD
Civil Protection - Marche Region
Meteo Section
Snow Section
Via del Colle Ameno 5
60126 Torrette di Ancona, Ancona
Uff: 071 806 7743
E-mail: stefano.so...@regione.marche.it
---Oo-oO

Da: Bert Gunter [bgunter.4...@gmail.com]
Inviato: venerdì 28 agosto 2020 18.07
A: Jeff Newmiller
Cc: Stefano Sofia; r-help mailing list
Oggetto: Re: [R] how to create a sequence to consecutive values

Actually, I prefer Jeff's use of diff() . Hadn't thought of that.

However, note that, unsurprisingly,  NA's mess up both: The rle() method fails 
with an error and the diff() method gives the wrong answer.

Cheers,
Bert


On Fri, Aug 28, 2020 at 8:48 AM Jeff Newmiller 
mailto:jdnew...@dcn.davis.ca.us>> wrote:
cumsum is a bit faster...

a <- c( 0, 0, 0, 1, 1, 1, 1, 0, 0, 0
  , 0, 1, 1, 0, 1, 1, 1, 0
  )

f1 <- function(a) {
  z <- rle(a)
  v <- z$values
  v[v==1] <- seq_along(v[v==1]) ## or use cumsum
  rep(v,z$lengths)
}

f2 <- function(a) {
  v <- cumsum( c( a[1], 1==diff(a) ) )
  v[ 0==a ] <- 0
  v
}

f2(a)

library(microbenchmark)

a2 <- rep( c( 0,0, 1, 1, 1 )
 , 300 )

microbenchmark( res1 <- f1(a2)
  , res2 <- f2(a2)
  )
stopifnot( res1 == res2 )


On August 28, 2020 8:19:41 AM PDT, Stefano Sofia 
mailto:stefano.so...@regione.marche.it>> wrote:
>Thank you!
>Stefano
>
> (oo)
>--oOO--( )--OOo
>Stefano Sofia PhD
>Civil Protection - Marche Region
>Meteo Section
>Snow Section
>Via del Colle Ameno 5
>60126 Torrette di Ancona, Ancona
>Uff: 071 806 7743
>E-mail: stefano.so...@regione.marche.it
>---Oo-oO
>
>Da: Bert Gunter [bgunter.4...@gmail.com]
>Inviato: venerd� 28 agosto 2020 17.14
>A: Stefano Sofia
>Cc: r-help mailing list
>Oggetto: Re: [R] how to create a sequence to consecutive values
>
>Using ?rle
>
>> z <- rle(a)
>> v <- z$values
>> v[v==1] <- seq_along(v[v==1]) ## or use cumsum
>< rep(v,z$lengths)
> [1] 0 0 0 1 1 1 1 0 0 0 0 2 2 0 3 3 3 0 0
>
>Cheers,
>Bert
>
>
>Bert Gunter
>
>"The trouble with having an open mind is that people keep coming along
>and sticking things into it."
>-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
>
>
>On Fri, Aug 28, 2020 at 7:52 AM Stefano Sofia
>mailto:stefano.so...@regione.marche.it>>>
>wrote:
>Dear R-list users,
>this is a simple question, I have not been able to find an efficient
>solution.
>Given a vector with only 0 or 1 values, I need to give a sequence to
>the consecutive values of 1:
>
>a <- c(0,0,0,1,1,1,1,0,0,0,0,1,1,0,1,1,1,0,0)
>
>I should get as result
>
>(0,0,0,1,1,1,1,0,0,0,0,2,2,0,3,3,3,0,0)
>
>I tried with ave, but no way to get it for me.
>
>Thank you for your help
>Stefano
>
> (oo)
>--oOO--( )--OOo
>Stefano Sofia PhD
>Civil Protection - Marche Region
>Meteo Section
>Snow Section
>Via del Colle Ameno 5
>60126 Torrette di Ancona, Ancona
>Uff: 071 806 7743
>E-mail:
>stefano.so...@regione.marche.it>
>---Oo-oO
>
>
>
>AVVISO IMPORTANTE: Questo messaggio di posta elettronica pu� contenere
>informazioni confidenziali, pertanto � destinato solo a persone
>autorizzate alla ricezione. I messaggi di posta elettronica per i
>client di Regione Marche possono contenere informazioni confidenziali e
>con privilegi legali. Se non si � il destinatario specificato, non
>leggere, copiare, inoltrare o archiviare questo messaggio. Se si �
>ricevuto questo messaggio per errore, inoltrarlo al mittente ed
>eliminarlo completamente dal sistema del proprio computer. Ai sensi
>dell�art. 6 della DGR n. 1394/2008 si segnala che, in caso di necessit�
>ed urgenza, la risposta al presente messaggio di posta elettronica pu�
>essere visionata da persone estranee al destinatario.
>IMPORTANT NOTICE: This e-mail message is intended to be received only
>by persons entitled to receive the confidential information it may
>contain. E-mail messages to clients of Regione Marche may contain
>information that is confidential and legally privileged. Please do not
>read, copy, forward, or store this message unless you are an intended
>recipient of it. If you have received this message in error, please
>forward it to the sender and delete it completely from your computer
>system.
>
>--
>Questo messaggio  stato analizzato da Libra ESVA ed  risultato non
>infetto.
>This message was scanned by Libra ESVA and is believed to be clean.
>
>
>[[alternative HTML version deleted]]
>
>__