【问题标题】:keeping certain rows in data frame with a condition保持数据框中的某些行有条件
【发布时间】:2019-09-23 18:37:27
【问题描述】:

我在 R 中有一个数据框,我想删除符合某些条件的某些行。我该怎么做?

我尝试过使用dplyrifelse,但我的代码没有给出正确答案

check8 <- distinct(df5,prod,.keep_all = TRUE)

不工作!给出整个数据集

输入是:

check1 <- data.frame(ID = c(1,1,2,2,2,3,4), 
                     prod = c("R","T","R","T",NA,"T","R"), 
                     bad = c(0,0,0,1,0,1,0))
  #     ID prod bad
#    1  1    R   0
#    2  1    T   0
#    3  2    R   0
#    4  2    T   1
#    5  2 <NA>   0
#    6  3    T   1
#    7  4    R   0

预期输出:

data.frame(ID = c(1,2,3,4), 
           prod = c("R","R","T","R"), 
           bad = c(0,0,1,0))


    #  ID prod bad
   # 1  1    R   0
   # 2  2    R   0
   # 3  3    T   1
   # 4  4    R   0

我希望得到这样的输出,对于同时存在 prod 或 NA 的 ID,只保留带有 prod R 的行,但如果只有一个 prod 则保留该行,尽管有 prod 。

【问题讨论】:

  • 这应该是输出 - data.frame(ID = c(1,2,3,4), prod = c("R","R","T","R" ), 坏 = c(0,0,1,0))
  • 嗨 Shaily,请在答案(可能已格式化)中包含预期的输出,并尝试更清楚地解释条件是什么,我很难理解您想要实现的目标。跨度>

标签: r if-statement dplyr


【解决方案1】:

这里使用anti_join的解决方案

library(dplyr)

check1 <- data.frame(ID = c(1,1,2,2,2,3,4), prod = c("R","T","R","T",NA,"T","R"), bad = c(0,0,0,1,0,1,0))

# First part: select all the IDs which contain 'R' as prod

p1 <- check1 %>% 
  group_by(ID) %>% 
  filter(prod == 'R')

# Second part: using anti_join get all the rows from check1 where there are not 
# matching values in p1

p2 <- anti_join(check1, p1, by = 'ID')

solution <- bind_rows(
  p1, 
  p2
) %>% 
  arrange(ID)

【讨论】:

    【解决方案2】:

    使用dplyr,我们可以使用filter 选择prod == "R" 所在的行,或者如果组中只有一行,则选择该行。

    library(dplyr)
    
    check1 %>%
      group_by(ID) %>%
      filter(prod == "R" | n() == 1)
    
    #     ID prod    bad
    #  <dbl> <fct> <dbl>
    #1     1 R         0
    #2     2 R         0
    #3     3 T         1
    #4     4 R         0
    

    【讨论】:

      猜你喜欢
      • 2015-07-01
      • 2016-09-10
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多