我想根据两个条件删除一些行。 这是我的代码
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
如果职业=文书和月度支出&gt;然后丢弃这些行 如果Occupation = management and MonthlySpend&gt; 57然后丢弃这些行。 最后我应该得到这个:
Occupation MonthlySpend
Clerical 58
Management 56
答案 0 :(得分:4)
使用OR组合所有条件:test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ) | !(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),]
像:
<include layout="@layout/content_detail" />
答案 1 :(得分:1)
步骤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)
第二步。加入并过滤
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
这样,您必须花费一些资源来定义第二个数据帧,但实际的过滤过程是简化的。