Max
Max

Reputation: 13

Multiply each row of a matrix which share same factor

I have a matrix in R of the following form. The first column is a unique value which is shared by 0

      [,1] [,2]
[1,]    1    4
[2,]    1    2
[3,]    2    3
[4,]    2    5
[5,]    3   10

Results should look like the following:

     [,1] [,2]
[1,]    1    8
[2,]    2   15
[3,]    3   10

I have been looking for some time online but cant find an answer to this 'simple' problem without subsetting. Thanks

Upvotes: 1

Views: 90

Answers (1)

akrun
akrun

Reputation: 886938

A simple option would be aggregate

aggregate(. ~ V1, as.data.frame(m1), FUN = prod)
#   V1 V2
#1  1  8
#2  2 15
#3  3 10

Or with tidyverse

library(dplyr)
library(tibble)
as_tibble(m1) %>% 
   group_by(V1) %>% 
   summarise_all(prod)

Or with split

sapply(split(m1[,2], m1[,1]), prod)

Upvotes: 2

Related Questions