[R] Bug in my code (finding nonzero min)

S Ellison S.Ellison at LGCGroup.com
Mon Jul 23 14:40:26 CEST 2012


Strictly, it's calculating the minimum of the positive values in each row.

And you could do that with a bit less code using 
q[,1] <- apply(remain, 1, function(x) min(x[x>0])) 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of wwreith
> Sent: 23 July 2012 05:35
> To: r-help at r-project.org
> Subject: [R] Bug in my code (finding nonzero min)
> 
> Can someone verify for me if the for loop below is really 
> calculating the nonzero min for each row of a matrix? I have 
> a bug somewhere in the is section of code. My first guess is 
> how I am find the the nonzero min of each row of my matrix. 
> The overall idea is to make sure I am investing all of my 
> money, i.e. new.set is a set of indicator variables for each 
> stock for a particular portfolio, i.e. 0=did not buy, 
> 1=bought. y are the stocks I could still buy, assuming I have 
> the money, data3[,5] are their cost, so for each portfolio, 
> i.e. the rows of new.set I have the option to purchase 
> another stock at a cost listed in the rows of variable 
> remain. Obvisouly the cheapest stock needs to have a cost>0 
> in order for me to be allowed to buy it. My code is intended 
> to weed out portfolios where I could have bought another 
> stock, by taking budget-portfolio cost - (cheapest available 
> stock) and subsetting new.set when this is negative, i.e. 
> buying the cheapest available stock puts me over budget. My 
> problem is that my code is still allowing examples like the 
> following budget of 10, portfolio cost 6, cheapest availabe 
> stock 3 despite the diff variable being negative.
> 
> Any ideas?
> 
> y<-1-new.set[,6:26]
> remain<-y*data3[,5]
> minn<-matrix(0,nrow(remain),1)
> 
> for(q in 1:nrow(remain))
> {
>   remainc<-remain[q,]
>   minn[q,]<-min(remainc[which(remainc>0)])
> }
> maxcost<-matrix(150,nrow(new.set),1)
> diff<-maxcost[,1]-new.set[,5]-minn[,1]
> new.set<-subset(new.set,diff<0)
> 
> 
> 
> 
> --
> View this message in context: 
> http://r.789695.n4.nabble.com/Bug-in-my-code-finding-nonzero-m
> in-tp4637399.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list