Skip to content
Prev 305439 / 398506 Next

[newbie] aggregating table() results and simplifying code with loop

Hello,

You would get more and better help if you were to break your problem 
into smaller sub-problems.
I am not really sure if this is what you want but here it goes.


inxList <- function(DF, logcover, nYears){
     f <- function(x, n){
         if(any(x)){
             r <- rle(x)
             any(r$lengths[!r$values] == n)
         }else FALSE
     }
     yrs <- lapply(0:5, `+`, seq_len(5))
     inx.list <- lapply(yrs, function(i){apply(logcover[, i], 1, f, 
nYears)})
     inx.list
}

makeCovers <- function(Cover, nYears){
     lcover <- T80[, ycols] == Cover
     inx.list <- inxList(T80[, ycols], lcover, nYears)
     tmp <- rep(NA, length(ws))
     names(tmp) <- ws
     xtb <- do.call(rbind, lapply(seq_along(inx.list), function(ix){
         xt <- xtabs(~ WS, T80[ inx.list[[ix]], c(2, 1 + ix + 1:5) ])
         tmp[names(xt)] <- xt; tmp}))
     colnames(xtb) <- paste("WS", seq_along(ws), sep = "")
     data.frame(xtb, Cover = Cover, Period = seq_along(inx.list))
}

T80 <- read.table("sample.txt", header=TRUE, sep = ";")

ycols <- grep("y", names(T80))
ws <- unique(T80$WS)
covers <- as.character(unique(unlist(T80[ycols])))

result <- lapply( 4:2, function(.n)
         do.call(rbind, lapply(covers, makeCovers, .n)) )
names(result) <- paste("nYears", 4:2, sep = ".")

str(result)
# See the results for 4 years
result[[ "nYears.4" ]]  # or any other number of years


Hope this helps,

Rui Barradas
Em 13-09-2012 14:36, Davide Rizzo escreveu: