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!