Another approach fun <- function(i, dat=x) { grp <- rep(1:(nrow(dat)/i), each=i) aggregate(dat[1:length(grp),]~grp, FUN=sum) }
lapply(2:6, fun, dat=TT) ------------------------------------- David L Carlson Department of Anthropology Texas A&M University College Station, TX 77840-4352 -----Original Message----- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Rui Barradas Sent: Thursday, September 25, 2014 3:34 PM To: eliza botto; r-help@r-project.org Subject: Re: [R] adding rows Hello, Try the following. fun <- function(x, r){ if(r > 0){ m <- length(x) %/% r y <- numeric(m) for(i in seq_len(m)){ y[i] <- sum(x[((i - 1)*r + 1):(i*r)]) } y }else{ NULL } } apply(TT, 2, fun, r = 2) apply(TT, 2, fun, r = 3) etc Hope this helps, Rui Barradas Em 25-09-2014 20:50, eliza botto escreveu: > Dear useRs, > Here is my data with two columns and 20 rows. >> dput(TT) > structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, > 19, 20, 24, 48, 72, 96, 120, 144, 168, 192, 216, 240, 264, 288, 312, 336, > 360, 384, 408, 432, 456, 480), .Dim = c(20L, 2L), .Dimnames = list(NULL, > c("", "SS"))) > I first of all want to sum up continuously two rows (1 & 2, 3 & 4, 5 & 6 and > so on) of each column. > Then I want to sum up 3 rows as (1-2-3,4-5-6,..... 16-17-18) and since 19th > and 20th rows do not up 3 rows, so they should be ignored. > Similarly with 4 sets of rows and 5 sets of rows and even 6. > I hope I was clear. > Thankyou so very much in advance, > Eliza > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.