[英]How do I only keep the rows with the lowest and highest value in a certain column, by groups?
[英]how to keep only rows that have highest value in certain column in R
我有一個看起來像這樣的 dataframe:
library(tidyverse)
df <- tribble (
~Species, ~North, ~South, ~East, ~West,
"a", 4, 3, 2, 3,
"b", 2, 3, 4, 5,
"C", 2, 3, 3, 3,
"D", 3, 2, 2, 2
)
我想過濾出最高值是北方的物種。 在這種情況下,將選擇物種 A 和 D。 預期的 output 將是一個 df,其中只有物種 A 和 D。 我使用了這樣的解決方法:
df %>%
group_by(species) %>%
mutate(rowmean = mean(North:West) %>%
filter(North > rowmean) %>%
ungroup() %>%
select(!rowmean)
這似乎是一個簡單任務的很多代碼。 但是,我無法找到一種對代碼更友好的方法? 是否有(最好是 tidyverse)以更干凈的方式執行此任務的方法?
親切的問候
一種更簡單的方法是在base R
max.col
Select 數字列。 獲取值為max
的每一行的列索引。 檢查是否等於 1 即第一列(因為我們僅從第二列開始選擇)並將行subset
subset(df, max.col(df[-1], 'first') == 1)
# A tibble: 2 x 5
# Species North South East West
# <chr> <dbl> <dbl> <dbl> <dbl>
#1 a 4 3 2 3
#2 D 3 2 2 2
如果它基於行均值
subset(df, North > rowMeans(df[-1]))
或者,如果我們更喜歡使用dplyr
library(dplyr)
df %>%
filter(max.col(cur_data()[-1], 'first') == 1)
同樣,如果它基於行均值
df %>%
filter(North > rowMeans(cur_data()[-1]))
# base
df[df$North > rowMeans(df[-1]), ]
# A tibble: 2 x 5
Species North South East West
<chr> <dbl> <dbl> <dbl> <dbl>
1 a 4 3 2 3
2 D 3 2 2 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.