【发布时间】:2016-06-04 18:34:35
【问题描述】:
我正在使用来自 R 的包 dplyr。我阅读了教科书和在线文章,但我无法弄清楚为什么这个功能不起作用。有人可以指出如何修复我的功能吗?
##creating dataset - this dataset is ranked by group (ID)
dt <- data.frame(
ID = c('A1','A2','A4','A2','A1','A4','A3','A2','A1','A3'),
Value = c(4,3,1,3,4,6,6,1,8,4));
dt2<-transform(dt, order.by.group =
ave(Value, ID, FUN = function(x) rank(x, ties.method = "first")))
##This function does not work, but it's supposed to create dt3 which is based
##on condition such as "best","worst" ranking etc in each ID group
test<- function(num="best") {
if (num=="best") {
dt3<-filter(dt2,order.by.group==1)}
else if (num=="worst") {
#sort to make low rank come to the last row position
dt2<-arrange(dt2,ID,order.by.group)
# Select the last row by id
dt3<-dt2[!duplicated(dt2$ID, fromLast=TRUE), ]}
else {dt3<-filter(dt2,order.by.group==num)}
}
【问题讨论】:
-
@MatthewLundberg 我不认为“=”有效。我收到错误消息说错误:过滤条件不评估为逻辑向量。
-
@ZheyuanLi 我检查了 ?filter 和示例用法。我看到“过滤器(mtcars,cyl == 8)”所以我认为它是这样使用的。我错过了什么吗?
-
@ZheyuanLi 我正在使用 R 的 dplyr 包。我还清除了我的工作空间,但我没有收到您的错误消息。我真的什么都没有得到,也没有执行。让我重新启动 R 并再次运行代码。
-
@ZheyuanLi 哦好的。当我运行 test("best") 或 test(2) 时,它不会产生 dt3,我也没有收到任何错误消息
标签: r function if-statement dplyr