Home > Blockchain >  How can I merge rows by a common variable and sum numeric columns while adding character rows to one
How can I merge rows by a common variable and sum numeric columns while adding character rows to one

Time:10-28

Below is a sample data frame of what I am working with.

df <- data.frame(
  Sample = c('A', 'A', 'B', 'C'),
  Length = c('100', '110', '99', '102'),
  Molarity = c(5,4,6,7)
)

df

  Sample Length Molarity
1      A    100        5
2      A    110        4
3      B     99        6
4      C    102        7

I would like the result listed below but am unsure how to approach the problem.

  Sample Length Molarity
1      A    100,110        9
2      B     99        6
3      C    102        7

CodePudding user response:

We may do group by summarisation

library(dplyr)
df %>%
   group_by(Sample) %>%
   summarise(Length = toString(Length), Molarity = sum(Molarity))

-output

# A tibble: 3 × 3
  Sample Length   Molarity
  <chr>  <chr>       <dbl>
1 A      100, 110        9
2 B      99              6
3 C      102             7

CodePudding user response:

A base R option:

df |>
  within({
    Length <- ave(Length, Sample, FUN = toString)
    Molarity <- ave(Molarity, Sample, FUN = mean)
    }) |>
  unique()

  Sample   Length Molarity
1      A 100, 110      4.5
3      B       99      6.0
4      C      102      7.0
  •  Tags:  
  • r
  • Related