0
options(scipen=999)
df <- data.frame(o=c('a','b','c','d'),
             a=c(200,200,200,200),
             b=c(20,20,20,20),
             c=c(10,10,10,10),
             d=c(100,100,100,100),
             e=c(2,2,2,2),
             f=c(50,50,50,50),
             g=c(200,200,200,200),
             h=c(20,20,20,20),
             i=c(10,10,10,10),
             stringsAsFactors = FALSE))

i <- 2
totals <- vector()

for (sets in 2:nrow(df)){
  x <- colSums(df[i:i], na.rm = TRUE)
  i <- i + 1
  y <- colSums(df[i:i], na.rm = TRUE)
  i <- i + 1
  z <- round(x/y,2)
  i <- i + 1
  totals <- c(totals,x,y,z)
}

totals <- unname(totals)
totals <- c("Totals",totals) #the issue is here
final <- rbind(df, totals)   #and here
print(final)

The first column of my DF are labels. I loop to do some calculations on the columns.

Then I want to bind the totals row with the dataframe. But first I add the word "Totals" to the start of my totals vector so that the column counts match.

Now the first column of the DF is the labels and the first column of the totals vector is "Totals".

But I get this error: Warning message: In [<-.factor(*tmp*, ri, value = 1L) : invalid factor level, NA generated

I've tried adding stringsAsFactors = FALSE to the DF and I've tried converting the totals vector to character, adding the label, and converting back to factor. Neither have worked.

  • Results: Warning message: In `[<-.factor`(`*tmp*`, ri, value = 0) : invalid factor level, NA generated > print(final) o a b c d e f g h i 1 a 200 20 10 100 2 50 200 20 10 2 b 200 20 10 100 2 50 200 20 10 3 c 200 20 10 100 2 50 200 20 10 4 d 200 20 10 100 2 50 200 20 10 5 800 80 10 400 8 50 800 80 10 – Katherine Lamoureux Nov 05 '20 at 14:27
  • `final <- rbind(df, data.frame(o = "Total", t(colSums(df[, -1]))))` – Ronak Shah Nov 05 '20 at 14:30

0 Answers0