0

I have data with 7 columns and 21 rows, and I want to create the for loop. I want to calculate the mean for first column in this data for fist 10 rows. And then I want to calculate second average for rows from 2 to 11, then from 3 to 12 and to the last from 11 to 20 row. I tried to do this by these code:

sredniaa <- array(0, 11)

for(j in 1:11) {
  sredniaa[j]<-mean(wartdop1[j:j+9,1])
}

but it doesn't work. Anyone know how to do that? My data is on image:

enter image description here

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Welcome to Stack Overflow. Please take time to read http://stackoverflow.com/help/how-to-ask. Take time to get your code formatting and typos out so people will take time to answer. – micstr Jan 29 '16 at 14:27
  • 1
    If you are okay with sharing data, pasting the result of `dput(wartdop1)` makes it easy for people to work around. – Kota Mori Jan 29 '16 at 14:29
  • Have you taken a look at http://stackoverflow.com/questions/19882085/subset-data-frame-in-r-using-loop and especially @Henriks comment which has two other links – micstr Jan 29 '16 at 14:32
  • at a guess....`require(zoo); rollapply( wartdop1[,1] , width=10 , partial=F )` – Simon O'Hanlon Jan 29 '16 at 14:34
  • @SimonO'Hanlon I think you either need to specify `FUN = mean` or use `rollmean`, but that's the neatest way. It's possible with only base R, too: `sapply(1:length(wartdop1[,1]), function(x){mean(wartdop1[x:(x+9), 1])})` – alistaire Jan 29 '16 at 14:50
  • 1
    @alistaire yes of course! Whoops. Clearly I meant to use `rollmean` rather than `rollapply`! `rollmean( wartdop1[,1] , width=10 , partial=F )`. And if one wanted to apply this to each column... `apply(wartdop1 , 2 , rollmean , width=10 , partial=F)` – Simon O'Hanlon Jan 29 '16 at 14:54
  • 1
    Your code is not wrong, you only have missing a couple of parentheses: `[j:j+9,1]` should be `[j:(j+9),1]`. – R. Schifini Jan 29 '16 at 16:10
  • Thanks R. Schifini, it helps and now it works! – Michał Krupa Jan 29 '16 at 17:53

0 Answers0