0

I got multiple dataframes of the same dimension within a single list. All dataframes are categorical, each has factorlevels. The columnnames of the dataframes are identical, in general they have the same factorlevels. It might be though that some factor levels don´t appear in all dataframes. I need to create a dataframe where each element is the mode (most frequently appearing element) of all elements at this position from all the dataframes. If there is a tie for the most frequent then just take one of those, be it the first, the last or an random one.

Thats how the data looks for example. df1,df2,df3,df4 are stored in the list df <- list(df1,df2,df3,df4)

df1
  col1 col2  col3
1    e    6 FALSE
2    b    1 FALSE
3    d    1  TRUE
4    e    2  TRUE
5    d    5  TRUE
> df2
  col1 col2  col3
1    b    2 FALSE
2    f    0  TRUE
3    e    5 FALSE
4    e    1  TRUE
5    b    1 FALSE
> df3
  col1 col2  col3
1    r    0  TRUE
2    d    1  TRUE
3    d    0 FALSE
4    b    5  TRUE
5    e    2  TRUE
> df4
  col1 col2  col3
1    d    5  TRUE
2    e    1  TRUE
3    b    2 FALSE
4    d    0  TRUE
5    e    5  TRUE

Desired result would be this. Hopefully made no mistake, this was done by hand.

  col1 col2  col3
1    e    6 FALSE
2    b    1  TRUE
3    d    1  FALSE
4    e    2  TRUE
5    e    5  TRUE

The given data can be recreated with the following code:

df1 = data.frame(col1 = c("e", "b", "d", "e", "d") ,
                 col2 = c(6, 1, 1, 2, 5),
                 col3= c(FALSE, FALSE, TRUE,TRUE, TRUE))
df1 <- data.frame(lapply(df1,factor))

df2 = data.frame(col1 = c("b", "f", "e", "e", "b") ,
                 col2 = c(2, 0, 5, 1, 1),
                 col3= c(FALSE, TRUE, FALSE,TRUE, FALSE))
df2 <- data.frame(lapply(df2,factor))

df3 = data.frame(col1 = c("r", "d", "d", "b", "e") ,
                 col2 = c(0, 1, 0, 5, 2),
                 col3= c(TRUE, TRUE, FALSE,TRUE, TRUE))
df3 <- data.frame(lapply(df3,factor))

df4 = data.frame(col1 = c("d", "e", "b", "d", "e") ,
                 col2 = c(5, 1, 2, 0, 5),
                 col3= c(TRUE, TRUE, FALSE,TRUE, TRUE))
df4 <- data.frame(lapply(df4,factor))

df <- list(df1,df2,df3,df4)   

Thanks a lot for the help!

Kevin
  • 47
  • 6

1 Answers1

2

You may add a position column in each list, combine them into one dataframe and find Mode for each position.

library(dplyr)
library(purrr)

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}


map_df(df, ~.x %>% mutate(position = row_number())) %>%
  summarise(across(everything(), Mode), .by = position) %>%
  select(-position)

#  col1 col2  col3
#1    e    6 FALSE
#2    b    1  TRUE
#3    d    1 FALSE
#4    e    2  TRUE
#5    e    5  TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks alot. Looks to be doing the correct thing. even though I don´t entirely understand what you´re doing. Sorry if that sounds rude but can anyone confirm that this works as intended? – Kevin May 21 '23 at 04:45