[R] crazy loop error.
Petr PIKAL
petr.pikal at precheza.cz
Tue Jan 25 17:42:22 CET 2011
Hi
r-help-bounces at r-project.org napsal dne 25.01.2011 10:58:36:
> ooh.. I have another question.
> What if I want to add the value in the vector a to the hello each time
it
> prints.
> Here is your output
>
> a <- c(2,3,5,5,5,6,6,7)
> mapply(rep, "hello", rle(a)$lengths, USE.NAMES = FALSE)
>
> [[1]]
> [1] "hello"
>
> [[2]]
> [1] "hello"
>
> [[3]]
> [1] "hello" "hello" "hello"
>
> [[4]]
> [1] "hello" "hello"
>
> [[5]]
> [1] "hello"
>
> If I want something like this, based on values in vector a.
Not sure how to use mapply
test<-vector("list", 5)
lll<-rle(a)
for (i in seq_along(lll$lengths)) test[[i]] <- rep(paste("hello",
lll$values[i]), lll$lengths[i])
>
> [[1]]
> [1] "hello 2"
>
> [[2]]
> [1] "hello 3"
>
> [[3]]
> [1] "hello 5" "hello 5" "hello 5"
>
> [[4]]
> [1] "hello 6" "hello 6"
>
> [[5]]
> [1] "hello 7"
>
> What i am actually doing is hmm.. I have a bunch of text files which is
> output from another program. I want to extract some specific information
> from these files and write to a new file and save it.
> All these files have a certain variable k which maybe 2, or 3 or 5 etc.
The
> vector a shows the k values of 8 of such files. I want the contents of
all
> files with k value 5 to be written into one file.
That is rather vague description. Does those files have some structure?
How do you know the variable k?
Loops are not so ineffective if you use them for what they are good and if
you do not expand the object within loop. See R-Inferno from P.Burns.
Regards
Petr
>
> Thanks,
> Roy
>
>
>
> On Mon, Jan 24, 2011 at 11:43 PM, Erik Iverson <eriki at ccbr.umn.edu>
wrote:
>
> >
> >
> > Roy Mathew wrote:
> >
> >> Thanks for the reply Erik, As you mentioned, grouping consecutive
elements
> >> of 'a' was my idea. I am unaware of any R'ish way to do it. It would
be nice
> >> if someone in the community knows this.
> >>
> >
> > Is this the idea you're trying to execute? It uses ?rle and ?mapply.
> >
> >
> > a <- c(2,3,5,5,5,6,6,7)
> > mapply(rep, "hello", rle(a)$lengths, USE.NAMES = FALSE)
> >
> > [[1]]
> > [1] "hello"
> >
> > [[2]]
> > [1] "hello"
> >
> > [[3]]
> > [1] "hello" "hello" "hello"
> >
> > [[4]]
> > [1] "hello" "hello"
> >
> > [[5]]
> > [1] "hello"
> >
>
>
>
> --
> Best Regards,
> Roy
>
> [[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.
More information about the R-help
mailing list