Özgür Asar
2012-May-31 06:08 UTC
[R] Warning message: numerical expression has 1000 elements: only the first used
Hi, Your mistake seems to be in sum(v[1:x]) You create "x" as a vector but your treat it as a single number. v[1:x] expects "x" to be a single number and only considers its first element which is 1. If I understand your query correctly, the following might handle your problem: sum.vec <-NULL for (x in 1:1000){ t <- rbinom(1000, 1, 0.5) v <- replace(t,t==0,-1) sum.vec<-c(sum.vec,sum(v[1:x])) } Best Ozgur ----- ************************************ Ozgur ASAR Research Assistant Middle East Technical University Department of Statistics 06531, Ankara Turkey Ph: 90-312-2105309 http://www.stat.metu.edu.tr/people/assistants/ozgur/ -- View this message in context: http://r.789695.n4.nabble.com/Warning-message-numerical-expression-has-1000-elements-only-the-first-used-tp4631813p4631903.html Sent from the R help mailing list archive at Nabble.com.
R. Michael Weylandt
2012-May-31 06:18 UTC
[R] Warning message: numerical expression has 1000 elements: only the first used
Ozgur -- No, this is not what the OP seems to be asking for (and it's bad code anyways -- I've mentioned the importance of pre-allocation to you before): OP, if I understand you, you are looking for a cumsum() operation: something like: t <- rbinom(1000, 1, 0.5) t[t==0] <- (-1) cumsum(t) Alternatively, noting that rbinom(, 1, ) gives only values of 0 and one, it's even faster to do: cumsum(2*rbinom(1000,1,0.5)-1) e.g., set.seed(1) t <- rbinom(1000, 1, 0.5) t[t==0] <- (-1) a <- cumsum(t) set.seed(1) b <- cumsum(2*rbinom(1000,1,0.5)-1) identical(a,b) # TRUE Best, Michael On Thu, May 31, 2012 at 2:08 AM, ?zg?r Asar <oasar at metu.edu.tr> wrote:> Hi, > > Your mistake seems to be in > > sum(v[1:x]) > > You create "x" as a vector but your treat it as a single number. > > v[1:x] expects "x" to be a single number and only considers its first > element which is 1. > > If I understand your query correctly, the following might handle your > problem: > > sum.vec <-NULL > for (x in 1:1000){ > t <- rbinom(1000, 1, 0.5) > v <- replace(t,t==0,-1) > sum.vec<-c(sum.vec,sum(v[1:x])) > } > > Best > Ozgur > > ----- > ************************************ > Ozgur ASAR > > Research Assistant > Middle East Technical University > Department of Statistics > 06531, Ankara Turkey > Ph: 90-312-2105309 > http://www.stat.metu.edu.tr/people/assistants/ozgur/ > -- > View this message in context: http://r.789695.n4.nabble.com/Warning-message-numerical-expression-has-1000-elements-only-the-first-used-tp4631813p4631903.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.