【问题标题】:dplyr and filter for conditional mutation but return full datasetdplyr 和过滤条件突变但返回完整数据集
【发布时间】:2022-01-17 16:19:35
【问题描述】:

我一直在使用 dplyr 和 filter 来创建基于几个因素的条件突变。但是,我需要这个新列的长度与原始数据集的长度相同,而不是只返回过滤后的结果。

使用下面的示例数据:我想创建一个名为 Result 的新列,并将每个 Condition 的行标记为“通过”,其中 Value 至少有两个不同的 Names 大于 3,否则标记为“失败”。注意-我想保留长格式的数据。

示例数据 + 我的努力:

data <- tibble(
  Condition = c(rep("Apple", 20),rep("Banana", 20),rep("Cherry", 20),rep("Pear", 20)),
  Names = c(rep("John", 5),rep("Paul", 5), rep("George", 5), rep("Ringo", 5), rep("John", 5),rep("Paul", 5),rep("George", 5),rep("Ringo", 5), rep("John", 5),rep("Paul", 5),rep("George", 5),rep("Ringo", 5),rep("John", 5),rep("Paul", 5),rep("George", 5), rep("Ringo", 5)),
  Value = c(rep(3, 5), rep(2, 5), rep(1, 5), rep(2, 5),rep(5, 5),rep(3, 5), rep(3, 5),rep(4, 5), rep(4, 5),rep(2, 5),rep(2, 5),rep(6, 5),rep(2, 5),rep(5, 5),rep(1, 5),rep(1, 5)))

x <- data %>%
  filter(Value >= 3) %>%
  group_by(Condition) %>%
  mutate(Result = ifelse(n_distinct(Names) >1, "pass", "fail"))

我追求的是什么:

desired <- tibble(
  Condition = c(rep("Apple", 20),rep("Banana", 20),rep("Cherry", 20),rep("Pear", 20)),
  Names = c(rep("John", 5),rep("Paul", 5), rep("George", 5), rep("Ringo", 5), rep("John", 5),rep("Paul", 5),rep("George", 5),rep("Ringo", 5), rep("John", 5),rep("Paul", 5),rep("George", 5),rep("Ringo", 5),rep("John", 5),rep("Paul", 5),rep("George", 5), rep("Ringo", 5)),
  Value = c(rep(3, 5), rep(2, 5), rep(1, 5), rep(2, 5),rep(5, 5),rep(3, 5), rep(3, 5),rep(4, 5), rep(4, 5),rep(2, 5),rep(2, 5),rep(6, 5),rep(2, 5),rep(5, 5),rep(1, 5),rep(1, 5)),
  Result = c(rep('fail',20),rep('pass',20),rep('pass',20),rep('fail',20))
)

谢谢

【问题讨论】:

    标签: r dplyr filter conditional-statements


    【解决方案1】:

    我们可以使用 n_distinct() 并对 n_distinct() 调用中的数据进行子集化。

    library(dplyr)
    
    output<-data %>%
            group_by(Condition) %>%
            mutate(Result = ifelse(n_distinct(Names[Value>3])>1,
                                   'pass',
                                   'fail')) %>%
            ungroup
    
    
    identical(output, desired)
    [1] TRUE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多