0

My data frame "c1"

 steps interval
   <dbl>    <int>
 1     0        0
 2     0        5
 3     0       10
 4     0       15
 5     0       20
 6     0       25
 7     0       30
 8     0       35
 9     0       40
10     0       45
# ... with 278 more rows

PS: Sorry for providing only a small sample from data

I want to create a new data frame 'c11' by adding the rows of "interval" column for every interval of 50, such that the sum of every 50 steps(column steps) is calculated accordingly.

My new data frame should look like

 steps interval
   <dbl>    <int>
 1     0        0
 2     0        50
 3     0       100
 4     10      150
 5     0       200
 6     6       250
 7     20      300
 8     0       350
 9     230     400
10     0       450

My code

n=0
j=0
y <- nrow(c1)/50
class(n)
c11 <- data.frame(matrix(NA, nrow = y, ncol = 2)) 

class(c11)
for (i in 1:nrow(c1)) {
  n <- n + c1[i,1]
  if (i%%50==0)
  {
    c11[j,1]<- i
    c11[j,2] <- n
    j <- j+1
    n = 0
  }

}

Can someone correct the code as it shows up the wrong output?

1
  • Not clear what you are trying to do. Please try and explain it better Commented Jun 21, 2019 at 10:03

1 Answer 1

1

Try using cut in aggregate

with(c1, aggregate(list(steps = steps), 
     list(interval = cut(interval, c(seq(min(interval), max(interval), 50), Inf), 
     labels = seq(min(interval), max(interval), 50), include.lowest = TRUE)), sum))

To make it more explicit, we can separate the steps

c1$group <- cut(c1$interval, c(seq(min(c1$interval), max(c1$interval), 50), Inf),
      labels = seq(min(c1$interval), max(c1$interval), 50), include.lowest = TRUE)

aggregate(steps~group, c1, sum)
Sign up to request clarification or add additional context in comments.

5 Comments

@AnanyaVidyanathan Can you explain what do you mean by not working ? did you get any error message or wrong answer? Also I had one typo in my earlier version. I have corrected it now. Can you try again ?
Error: in aggregate.data.frame(as.data.frame(x), ...) : no rows to aggregate
@AnanyaVidyanathan I created a new column with cut. Can you try that now and let me know.
Yea @Ronak Shah it's working perfectly....Thanks, man.... btw would mind finding what is wrong in my code?
@AnanyaVidyanathan The one main thing I could see you are iterating over every row which doesn't look correct as you want to sum every 50 interval and not rows. Also usually, in R most of the times you could get away without using loops using functions like aggregate/dplyr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.