Skip to content
Prev 178017 / 398502 Next

function output with for loop and if statement

On Wed, 2009-04-22 at 15:51 -0400, aaron wells wrote:
It would help a lot if you spaced your code out a bit around key
operators and structural elements.

Anyway, you didn't enclose the if/else blocks in {} in such cases, only
the line following the if(...) is run if the clause is TRUE - the lines
after that, but the code you provided doesn't even load into R - the
lone else is a syntax error. So it is a bit difficult to see what is
going on and you don;t provide an example any of us can reproduce as we
don't have your data objects.

I edited your functions below to do what I think you intended and to
clean it up a bit. Perhaps we can use this as starting point if the
function here:

`concov.test` <- function(vegetation, specieslist)
{
    test.veg <- vegetation
    names(test.veg) <- specieslist$LifeForm
    nams <- unique(names(test.veg))
    tmp <- matrix(nrow = nrow(test.veg), ncol = length(nams))
    for (i in nams) {
        test.out <- apply(test.veg[, names(test.veg)==i], 1, sum)
        tmp.match <- nams[nams==i]
        tmp.col <- match(tmp.match, nams)
        tmp[1:nrow(test.veg), tmp.col] <- test.out
        tmp.out <- data.frame(row.names(test.veg), tmp, row.names = 1)
        names(tmp.out) <- nams
        ## do you need this or is this for debugging?
        print(tmp.out)
        tmp.out.sort <- tmp.out[, order(names(tmp.out))]
    }
    if(table(names(tmp.out))[i] == 1) {
        nams.srt <- names(tmp.out.sort)
        tmp.match2 <- nams.srt[nams.srt == i]
        tmp.col2 <- match(tmp.match2, names.srt)
        tmp.out.sort[1:nrow(test.veg), tmp.col2] <-
            test.veg[, names(test.veg)==i]
        return(tmp.out.sort)
    } else {
        return(tmp.out.sort)
    }
}

doesn't do what you want. Please provide a small, reproducible example
(that means with data, dummy or otherwise) so we can run the code and
test changes against your data.

HTH

G