Hi I read textbook and online articles, but I just cannot figure out why this function is not working.. Can someone please point out how to fix my function?
##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)}}
When I do test() I get
Error in filter(dt2, order.by.group == 1) (from #3) :
object 'order.by.group' not found
In addition: Warning message:
In data.matrix(data) : NAs introduced by coercion
I don't get that error. It just doesn't execute. Plus, I have order.by.group in dt2.
Aucun commentaire:
Enregistrer un commentaire