[英]Compare multiple columns in different data frames R
我有三個數據框:
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"))
我想比較三個不同數據框中的“值”列。 比較這些,我想找出其中哪些(總共)具有最低值。 例如,dat3 具有三個數據幀中的最低值。 我沒有得到compare
function 的工作。 有什么想法嗎?
一個基礎 R 選項
which.min(
colSums(`class<-`(
sapply(
list(dat1, dat2, dat3),
`[[`, "Value"
), "numeric"
))
)
# [1] 3
我們可以使用tidyverse
library(dplyr)
library(purrr)
mget(ls(pattern = '^dat\\d+$')) %>%
map_dbl(~ .x %>%
pull(Value) %>%
as.numeric %>%
sum) %>%
which.min
#dat3
# 3
將數據框放在一個列表中,您可以對每個數據框的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.