1

I have the following matrix:

Fruits  Person1  Person2  Person3
Apple   2        4        0
Apple   2        0        8
Orange  1        3        0

I would like to move up the value of the rows where the fruits are same.

The final output would be like this:

Fruits  Person1  Person2  Person3
Apple   2        4        8
Orange  1        3        0
Sarah
  • 55
  • 4

2 Answers2

4

We can do a group by 'Fruits' and summarise across the numeric columns to get the max value

library(dplyr)
df1 %>%
   group_by(Fruits) %>%
   summarise(across(where(is.numeric), max))

-output

# A tibble: 2 x 4
#  Fruits Person1 Person2 Person3
#* <chr>    <int>   <int>   <int>
#1 Apple        2       4       8
#2 Orange       1       3       0

Or using collapse

library(collapse)
g <- GRP(df1, ~ Fruits)
fmax(df1[-1], g)
#       Person1 Person2 Person3
#Apple        2       4       8
#Orange       1       3       0

data

df1 <- structure(list(Fruits = c("Apple", "Apple", "Orange"), Person1 = c(2L, 
2L, 1L), Person2 = c(4L, 0L, 3L), Person3 = c(0L, 8L, 0L)),
class = "data.frame", row.names = c(NA, 
-3L))
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Maybe aggregate helps

> aggregate(. ~ Fruits, df, max)
  Fruits Person1 Person2 Person3
1  Apple       2       4       8
2 Orange       1       3       0

Data

> dput(df)
structure(list(Fruits = c("Apple", "Apple", "Orange"), Person1 = c(2L,
2L, 1L), Person2 = c(4L, 0L, 3L), Person3 = c(0L, 8L, 0L)), class = "data.frame", row.names = 
c(NA,
-3L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81