Ananya Vidyanathan
Ananya Vidyanathan

Reputation: 51

Forming a new dataframe from the old data frame using for-loop

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?

Upvotes: 0

Views: 76

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

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)

Upvotes: 1

Related Questions