【问题标题】:Delete rows based on multiple conditions in r [duplicate]根据r中的多个条件删除行[重复]
【发布时间】:2017-09-12 17:19:54
【问题描述】:

我想根据两个条件删除一些行。 这是我的代码

test <-datasetjoin[!(datasetjoin$Occupation == "Clerical" & datasetjoin$AvgMonthSpend > 58.515 ),]  
test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ),] 
test <- test[!(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),] 
test <- test[!(test$Occupation == "Professional" & test$AvgMonthSpend > 60.08 ),]   
test <- test[!(test$Occupation == "Skilled Manual" & test$AvgMonthSpend > 57.06 ),] 
test <- test[!(test$NumberCarsOwned == "1" & test$YearlyIncome > (81300-51140) * 1.5 + 81300),] 

是否有可能以更优雅的方式获得相同的结果?

提前致谢

Occupation MonthlySpend 
Clerical   60           
Management 59           
Clerical   62           
Clerical   58           
Clerical   63              
Management 56
Management 58      

如果 Occupation = clerical 且 MonthlySpend > 60,则删除这些行 如果 Occupation = management 且 MonthlySpend > 57,则删除这些行。 最后我应该得到这个:

Occupation MonthlySpend
Clerical   58
Management 56

【问题讨论】:

  • 您的问题请提供reproducible examples
  • @AdamQuek 请检查帖子,我编辑了一个示例。有没有办法用循环来做到这一点?或应用()?

标签: r


【解决方案1】:

使用 OR 组合所有条件:|

喜欢:

test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ) | !(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),] 

【讨论】:

  • 简单漂亮,谢谢:)
【解决方案2】:

你可以试试这样的。

步骤 1. 定义限制:

df <- read.table(text="Occupation MonthlySpend 
Clerical   60           
Management 59           
Clerical   62           
Clerical   58           
Clerical   63              
Management 56
Management 58 ", stringsAsFactors=FALSE, header = TRUE)


df2 <- read.table(text="Occupation lmt 
Clerical   60           
Management 57           
", stringsAsFactors=FALSE, header = TRUE)

步骤 2。加入和过滤

df %>% left_join(df2, by = "Occupation") %>%
  group_by(Occupation) %>%
  filter(MonthlySpend < lmt ) %>%
  select(MonthlySpend)

给出:

Source: local data frame [2 x 2]
Groups: Occupation [2]

  Occupation MonthlySpend
       <chr>        <int>
1   Clerical           58
2 Management           56

这样,您必须花费一些资源来定义第二个数据帧,但实际的过滤过程被简化了。

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2018-06-12
    • 2022-08-15
    • 2021-02-24
    • 1970-01-01
    • 2019-02-13
    • 2015-09-24
    • 2020-05-22
    • 2020-09-02
    相关资源
    最近更新 更多