0

I have been trying to produce a command in R that allows me to produce a new vector where each row is the sum of 25 rows from a previous vector.

I've tried making a function to do this, this allows me to produce a result for one data point.

I shall put where I haver got to; I realise this is probably a fairly basic question but it is one I have been struggling with... any help would be greatly appreciated;

example<-c(1;200)


fun.1<-function(x)
{sum(x[1:25])}

checklist<-sapply(check,FUN=fun.1)

This then supplies me with a vector of length 200 where all values are NA.

Can anybody help at all?

Andrie
  • 176,377
  • 47
  • 447
  • 496
Ash
  • 73
  • 2
  • 6
  • what is `check`variable here? Is 25 rows constant or you need to define your question properly. If it is the same 25 rows, you don't need a 'sapply` just `rep` will do it. – Subs Jun 07 '12 at 11:22
  • Almost identical to http://stackoverflow.com/q/7822448/602276. There is a search button at the top of the page. Type `[r] cumulative sum` to get a list of very similar questions. – Andrie Jun 07 '12 at 11:26
  • 1
    The solution there using embed is going to be faster than the one below. This should be closed. – IRTFM Jun 07 '12 at 12:46
  • I think @Matthew Dowle's answer here would be of interest too: http://stackoverflow.com/questions/10837258/r-ddply-with-fixed-number-of-rows/10838040#10838040 – Chase Jun 07 '12 at 13:18
  • Since you're unclear on the difference between a vector and a matrix, you'd probably benefit from reading the R tutorials available at cran.r-project.org and many other places on the web. – Carl Witthoft Jun 07 '12 at 14:45

1 Answers1

2

Your example is a bit noisy (e.g., c(1;200) has no meaning, probably you want 1:200 there, or, if you would like to have a list of lists then something like rep, there is no check variable, it should have been example, etc.).

Here's the code what I think you need probably (as far as I was able to understand it):

x <- rep(list(1:200), 5)
f <- function(y) {y[1:20]}
sapply(x, f)

Next time please be more specific, try out the code you post as an example before submitting a question.

rlegendi
  • 10,466
  • 3
  • 38
  • 50