maximusdooku
maximusdooku

Reputation: 5512

How can I add rows into a single row?

I have a tibble:

# A tibble: 10 x 2
   term                sumsq
   <chr>               <dbl>
 1 a1                 10.1  
 2 a2                 5.15 
 3 a3                 45.1  
 4 a4                 7.32 
 5 a1:a2              0.870
 6 a1:a3              14.1  
 7 a1:a4              12.0  
 8 a2:a4              0.211
 9 a2:a3              0.305
10 Residuals          4.88 

How can I add rows 5-9 and add them into a new row and drop the original rows?

Desired output?

   term                sumsq
   <chr>               <dbl>
 1 a1                 10.1  
 2 a2                 5.15 
 3 a3                 45.1  
 4 a4                 7.32 
 5 Interactions       27.486
10 Residuals          4.88 

Note: 0.870+14.1+12.0+0.211+0.305=27.486

Tried

df %>% 
 slice(., 5:9)

Upvotes: 0

Views: 46

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

We can divide the data in two parts row 5 and 9 and all others. We take the sum of second part and add it to first part.

library(dplyr)

df %>%
   slice(-(5:9)) %>%
    bind_rows(df %>%
               slice(5:9) %>%
                summarise(term = "Interaction",
                          sumsq = sum(sumsq)))

#         term  sumsq
#1          a1 10.100
#2          a2  5.150
#3          a3 45.100
#4          a4  7.320
#5   Residuals  4.880
#6 Interaction 27.486

Similar in Base R

rbind(df[-c(5:9), ], data.frame(term = "Interaction", sumsq = sum(df$sumsq[5:9])))

Upvotes: 1

Related Questions