Skip to content
Prev 313954 / 398506 Next

"For" loop and "if" question

Hello,

Thanks for the data example.
Try the following.


fun <- function(DF){
     f <- function(x, y){
         if(ncol(y) == 3) rbind(x, y) else x
     }

     p <- grep("^p[[:digit:]]+$", names(DF))
     lat <- grep("^lat[[:digit:]]+$", names(DF))
     long <- grep("^long[[:digit:]]+$", names(DF))
     p <- sapply(DF[p], as.logical)
     lat <- sapply(DF[lat], as.numeric)
     long <- sapply(DF[long], as.numeric)

     tmp <- sapply(seq_len(ncol(p)), function(j)
         cbind(p = j, lat = lat[p[, j], j], long = long[p[, j], j]))
     tmp <- na.omit(Reduce(f, tmp))
     data.frame(tmp, row.names = seq_len(nrow(tmp)))
}

fun(dat)  # 'dat' is your data example, dat <- structure(...)


Hope this helps,

Rui Barradas
Em 19-12-2012 20:56, Steven Ranney escreveu: