paula456
paula456

Reputation: 111

Compare multiple columns in different data frames R

I have three data frames:

dat1 <-  data.frame( "ID" = c("1","2","3","4","5"), Value = c("32", "54", "67", "81", "12"))
dat2 <-  data.frame( "ID" = c("1","2","3","4","5"), Value = c("50", "90", "21", "45", "34"))
dat3 <-  data.frame( "ID" = c("1","2","3","4","5"), Value = c("2", "67", "87", "32", "15"))

I would like to compare the column "Value" in the three different data frames. Comparing these, I would like to find out which of them has (in total) the lowest values. For example, dat3 has the lowest values of the three data frames. I didn't get the compare function to work. Any thoughts?

Upvotes: 0

Views: 129

Answers (3)

akrun
akrun

Reputation: 887118

We can use tidyverse

library(dplyr)
library(purrr)
mget(ls(pattern = '^dat\\d+$')) %>%
     map_dbl(~ .x %>%
                   pull(Value) %>%
                   as.numeric %>%
                   sum) %>% 
    which.min
#dat3 
#   3 

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

A base R option

which.min(
  colSums(`class<-`(
    sapply(
      list(dat1, dat2, dat3),
      `[[`, "Value"
    ), "numeric"
  ))
)
# [1] 3

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

Put the dataframes in a list, you can sum the Value column from each and get the index of minimum value with which.min.

list_df <- list(dat1, dat2, dat3)
which.min(sapply(list_df, function(x) sum(as.numeric(x$Value))))
#[1] 3

Upvotes: 1

Related Questions