The for loop is executing 15 times. This results in i increasing up to 47 which is greater than the number of columns in df.

Change to a while loop which checks the value of i.

i <- 2
while (i + 2 <= ncol(df)) {
  x <- colSums(df[i], na.rm = TRUE)
  i <- i + 1
  y <- colSums(df[i], na.rm = TRUE)
  i <- i + 1
  z <- round(x / y,2)
  i <- i + 1
  totals_list <- c(totals_list, x, y, z)
}

totals_list <- c("Totals", totals_list)
totals_df <- as.data.frame(totals_list, stringsAsFactors=FALSE)
totals_df <- setNames(totals_df, names(df))
final <- rbind(df, totals_df)
print(final)
#>       X0   a  b  c   d e  f   g  h  i   j  k  l   m n  o
#> 1      a 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 2      b 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 3      c 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 4      d 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 5 Totals 800 80 10 400 8 50 800 80 10 800 80 10 400 8 50

This can also be written like this.

totals <- colSums(df[-1])

every_third_index <- which(seq_along(totals) %% 3 == 0)
totals[every_third_index] <- totals[every_third_index - 2] / totals[every_third_index - 1]

rbind(df, c("Totals", totals))
#>       X0   a  b  c   d e  f   g  h  i   j  k  l   m n  o
#> 1      a 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 2      b 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 3      c 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 4      d 200 20 10 100 2 50 200 20 10 200 20 10 100 2 50
#> 5 Totals 800 80 10 400 8 50 800 80 10 800 80 10 400 8 50

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top