Home > Software engineering >  Sum While melting columns in R
Sum While melting columns in R

Time:05-29

Is there a way to melt 2 columns and take there sums as value . For example

df <- data.frame(A = c("x", "y", "z"), B = c(1, 2, 3), Cat1 = c(1, 4, 3), New2 = c(4, 4, 4))

Expected output

New_Col  Sum
Cat1      8
New2      12

CodePudding user response:

Or using base R with colSums after selecting the columns of interest and then convert the named vector to data.frame with stack

stack(colSums(df[c("Cat1", "New2")]))[2:1]
   ind values
1 Cat1      8
2 New2     12

CodePudding user response:

Of course

df %>% 
    summarise(across(starts_with('Cat'), sum)) %>% 
    pivot_longer(everything(), names_to = 'New_Col', values_to = 'Sum')
# A tibble: 2 × 2
  New_Col   Sum
  <chr>   <dbl>
1 Cat1        8
2 Cat2       12
  •  Tags:  
  • r
  • Related