[R] how to save this result in a vector
Joshua Wiley
jwiley.psych at gmail.com
Mon Nov 1 02:03:08 CET 2010
On Sun, Oct 31, 2010 at 5:44 PM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
<snip>
> #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)
> }
I did not catch that i was not necessarily starting at 1 going
sequentially up, so that would have to be done manually (or use cumsum
per David rather than the function you wrote).
cover_per2 <- function(cover) {
output <- vector("numeric", length(min(cover):max(cover)))
j <- 1
for (i in min(cover):max(cover)) {
output[j] <- 100*sum(ifelse(cover >= i, 1, 0))/length(cover)
j <- j + 1
}
return(output)
}
Josh
More information about the R-help
mailing list