[英]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.
例如,dat3 具有三个数据帧中的最低值。 I didn't get the
compare
function to work.我没有得到
compare
function 的工作。 Any thoughts?有什么想法吗?
A base R option一个基础 R 选项
which.min(
colSums(`class<-`(
sapply(
list(dat1, dat2, dat3),
`[[`, "Value"
), "numeric"
))
)
# [1] 3
We can use tidyverse
我们可以使用
tidyverse
library(dplyr)
library(purrr)
mget(ls(pattern = '^dat\\d+$')) %>%
map_dbl(~ .x %>%
pull(Value) %>%
as.numeric %>%
sum) %>%
which.min
#dat3
# 3
Put the dataframes in a list, you can sum
the Value
column from each and get the index of minimum value with which.min
.将数据框放在一个列表中,您可以对每个数据框的
Value
列sum
,并使用which.min
获取最小值的索引。
list_df <- list(dat1, dat2, dat3)
which.min(sapply(list_df, function(x) sum(as.numeric(x$Value))))
#[1] 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.