[R] Find the maximum value of a column in a matrix

arun smartpink111 at yahoo.com
Sat Jan 11 16:00:26 CET 2014


HI,
The input and output dataset looks different (typo?) in "profit" column.
dat1 <- read.table(text="Place  Prod  Loctn  profit
S1     P1     Loc1    55
S1     P2     Loc1   80
S1     P3     Loc2   70
S1     P1     Loc2   60
S2     P2     Loc1   30    
S2     P3     Loc1   40
S2     P1     Loc1   15
S2     P2     Loc2   20",sep="",header=TRUE,stringsAsFactors=FALSE)

dat2 <- within(dat1,solution<-(ave(profit,Loctn,Place,FUN=max)==profit)*1)
dat2$solution
[1] 0 1 1 0 0 1 0 1 ##Also, based on the question, the last entry seems to be 1??
A.K.




Hi All, 

I have following matrix: 

Place  Prod  Loctn  profit 
S1     P1     loc1    55 
S1     P2     Loc1   80 
S1     P3     Loc2   70 
S1     P1     Loc2   90 
S2     P2     Loc1   30     
S2     P3     Loc1   40 
S2     P1     Loc2   15 
S2     P2     Loc2   20 

I want for each place, which product is giving maximum profit at each location and output should be in following form 

Place  Prod  Loctn  profit  solution 
S1     P1     loc1    55           0 
S1     P2     Loc1   80           1 
S1     P3     Loc2   70           1             
S1     P1     Loc2   60           0 
S2     P2     Loc1   30           0     
S2     P3     Loc1   40           1           
S2     P1     Loc1   15           0 
S2     P2     Loc2   20           0 

Thanks in advance



More information about the R-help mailing list