你好,这是我的第一篇文章
我希望能够正确并且可以被复制。
我在想,是否有比我下面的方法更优雅的解决方案
我有一个数据框架,并想使用条件过滤器提取符合这些条件的行。
输出时,我希望得到满足不同列的条件的前top_n行,同时保留所有其他列。
数据框架示例:
set.seed(123)
df1 <- data.frame(
A = as.numeric(1:10),
B = sample(seq(as.Date('2000/01/01'), as.Date('2018/01/01'), by="day"), size=10),
C = as.numeric(sample(20:90, size = 10)),
D = sample(c("yes", "no"), size=10, replace = TRUE),
E = as.numeric(sample(1000:2000, size = 10))
)
df1 #check output
> df1 #check output
A B C D E
1 1 2005-03-06 87 no 1963
2 2 2014-03-11 51 no 1902
3 3 2007-05-12 66 no 1690
4 4 2015-11-22 58 no 1793
5 5 2016-12-02 26 no 1024
6 6 2000-10-26 79 no 1475
7 7 2009-07-01 35 no 1754
8 8 2016-01-19 22 no 1215
9 9 2009-11-30 40 yes 1315
10 10 2008-03-17 85 yes 1229
需要过滤的条件:
A)如果E列的值在1000至1500之间,则返回前2行,以A列为权重
B)如果E列的值在1000至2000之间,则返回前2行,以B列为权重
C)如果E列的值在1000至1400之间,则返回前2行,以C列为权重
我已经想出了以下解决方案,但它很繁琐,不知道是否有更好的方法。
library("dplyr")
library("tidyr")
A<- df1 %>% dplyr::filter(E >= 1000 & E <= 1500) %>% top_n( n = 2, wt = A) %>% arrange(-A) %>% mutate(condition = "-cond_A")
B<- df1 %>% dplyr::filter(E >= 1000 & E <= 2000) %>% top_n( n = 2, wt = B) %>% arrange(B) %>% mutate(condition = "cond_B")
C<- df1 %>% dplyr::filter(E >= 1000 & E <= 1400) %>% top_n( n = 2, wt = C) %>% arrange(-C) %>% mutate(condition = "-cond_C")
我期望的输出是以下内容:
spread(as.data.frame(distinct(bind_rows(A,B,C))),condition, condition)
A B C D E -cond_A -cond_C cond_B
1 5 2016-12-02 26 no 1024 <NA> <NA> cond_B
2 8 2016-01-19 22 no 1215 <NA> <NA> cond_B
3 9 2009-11-30 40 yes 1315 -cond_A -cond_C <NA>
4 10 2008-03-17 85 yes 1229 -cond_A -cond_C <NA>