mardi 7 juillet 2015

If else statement for a list with matrices

I am learning how to properly set up loops but still struggle with the correct indexing and syntax. Below I have a list of two matrices, 2 columns x 3 rows each. I want to look at the second column in each matrix, and create ideally a new column with values 1 if x>0.50, else = 0. Help will be much appreciated for both ways to do it, it should help me learn. Also, if you know any good reference of structuring loops in higher dimensional lists it would be much appreciated. Thanks so much.

a <- c(0.1,0.2,0.3)
b <- c(0.8,0.2,0.5)
c <- c(0.4,0.9,1.0)
d <- c(0.7,0.9,0.2)
ab <- cbind(a,b)
cd <- cbind(c,d)
abcd <- list(ab,cd)

presabs <- vector("list",ncol(y))

# Trying lapply but indexing something wrong
res <- lapply(abcd, function(x) if (x[,2]>0.5) {1} else {0})

# Other method also not working:

for (i in 1:length(abcd))
        for (j in 1:length(a)){
                {
                if(abc[[i]][j]>0.50){
                        presabs[j] <- 1
                } else {
                        presabs[j] <- 0
                }
        }
}

Aucun commentaire:

Enregistrer un commentaire