[R] how to save this result in a vector

Joshua Wiley jwiley.psych at gmail.com
Mon Nov 1 01:44:57 CET 2010


Hi Changbin,

The yek is that you need to save the results of your for loop rather
than just printing it.  It also may be possible to vectorize your for
loop which might simplify things and speed them up, but I did not look
at that.  Here is one way to save the results, see inline comments for
more details.

Cheers,

Josh


##############################

test<-seq(10, 342, by=2)

#cover is a vector
cover_per <- function(cover) {
  ## create a vector to store the results of your for loop
  output <- vector("numeric", length(min(cover):max(cover)))
  for (i in min(cover):max(cover)) {
    ## rather than print()ing the output, assign it to an object
    output[i] <- 100*sum(ifelse(cover >= i, 1, 0))/length(cover)
  }
  ## have the return value from the function be
  ## the object 'output'
  return(output)
}

## here the results will be printed to the screen
## (the results are just the 'output' object)
cover_per(test)
## if you assign it to another object, nothing is printed
## but you can easily print 'result' if you want
result <- cover_per(test)

##############################


On Sun, Oct 31, 2010 at 5:35 PM, Changbin Du <changbind at gmail.com> wrote:
> HI, Dear R community,
>
> I have the following codes to calculate the commulative coverage. I want to
> save the output in a vector, How to do this?
>
> test<-seq(10, 342, by=2)
>
> #cover is a vector
> cover_per<-function (cover) {
> for (i in min(cover):max(cover)) {print(100*sum(ifelse(cover >= i, 1,
> 0))/length(cover))}
> }
>
> result<-cover_per(test)
>
>> result
> NULL
>
> Can anyone help me this this?
>
>
>
>
> --
> Sincerely,
> Changbin
> --
>
>        [[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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list