【问题标题】:Filter column based on other character column (in R)根据其他字符列过滤列(在 R 中)
【发布时间】:2021-11-30 04:26:51
【问题描述】:

我想使用dplyr,这样当两行标签相同但类型不同时,只保留类型为“大”的那一行。

当前结构

df <- data.frame(Label = c("A", "A", "B", "C", "C", "D"), Type = c("big", "small", "big", "small", "tall", "short"))

所需的df

df_clean <- data.frame(Label = c("A", "B", "C", "D"), Type = c("big", "big", "tall", "short"))

前提是big > smalltall > small

PD:我的真实数据框有其他类别,但也有层次结构。

谢谢!

【问题讨论】:

标签: r dplyr filter


【解决方案1】:

这行得通吗:

library(dplyr)

df %>% group_by(Label) %>% filter(if(n() > 1) Type == 'big' else TRUE)
# A tibble: 3 x 2
# Groups:   Label [3]
  Label Type 
  <chr> <chr>
1 A     big  
2 B     big  
3 C     small

【讨论】:

  • 它并不完全有效,因为我的真实数据集中有几个层次结构。 df &lt;- data.frame(Label = c("A", "A", "B", "C", "C", "D"), Type = c("big", "small", "big", "small", "tall", "short")) 如果我们添加类别“高”、“矮”,我希望 A 为“大”(大>小),C 为“高”(高>小)
【解决方案2】:
df1 <- data.frame(Label = c("A", "A", "B", "C", "C", "D"), 
                  Type = c("big", "small", "big", "small", "tall", "short"))

这个解决方案也适用于新的约束,只要优先顺序是

大>高>小>短

(和你的要求一样,只是如果big和tall一起出现,会选择big(和small分别))

library(dplyr)
df1 %>% 
  mutate(Type = factor(Type, levels = c( "big", "tall", "small", "short"))) %>% 
  group_by(Label) %>% 
  arrange(Type) %>% 
  summarise(Type = first(Type))

返回:

  Label Type 
  <chr> <fct>
1 A     big  
2 B     big  
3 C     tall 
4 D     short

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2019-06-15
    • 1970-01-01
    • 2023-01-30
    • 2022-12-21
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多