比较不同数据框 R 中的多列

问题描述

我有三个数据框:

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

我想比较三个不同数据框中的“值”列。比较这些,我想找出其中哪一个(总共)具有最低值。例如,dat3 具有三个数据帧中的最低值。我没有让 compare 函数起作用。有什么想法吗?

解决方法

基本的 R 选项

        ReformZoneCode   value  name
0                  210  141       a
1      210;221;222;223  142       b
2  210;221;222;231;234  143       c
3  210;222;223;232;233  144       d
4          221;231;234  145       e
,

我们可以使用tidyverse

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

将数据框放在一个列表中,您可以sum从每个列中Value列并使用which.min获取最小值的索引。

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