sapply(1:4, FUN=function(i, x, UB=c(2.5, 5.5, 8.5, 10.5)) {result <- x[,i]; result[result > UB[i]] <- UB[i]; result}, x=somematrix)
On Wed, May 27, 2020 at 1:46 PM Michael Ashton <m.ash...@enduringinvestments.com> wrote: > > Hi - > > I have a matrix of n rows and 4 columns. > > I want to cap the value in each column by a different upper bound. So, > suppose my matrix is > > somematrix <- matrix(c(1,4,3,6,3,9,12,8,5,7,11,11),nrow=3,ncol=4) > > somematrix > [,1] [,2] [,3] [,4] > [1,] 1 6 12 7 > [2,] 4 3 8 11 > [3,] 3 9 5 11 > > Now I want to have the maximum value in each column described by > UB=c(2.5, 5.5, 8.5, 10.5) > > So that the right answer will look like: > [,1] [,2] [,3] [,4] > [1,] 1 5.5 8.5 7 > [2,] 2.5 3 8 10.5 > [3,] 2.5 5.5 5 10.5 > > I've tried a few things, like: > newmatrix <- apply(somematrix,c(1,2),function(x) min(UB,x)) > > but I can't figure out to apply the relevant element of the UB list to the > right element of the matrix. When I run the above, for example, it takes > min(UB,x) over all UB, so I get: > > newmatrix > [,1] [,2] [,3] [,4] > [1,] 1.0 2.5 2.5 2.5 > [2,] 2.5 2.5 2.5 2.5 > [3,] 2.5 2.5 2.5 2.5 > > I'm sure there's a simple and elegant solution but I don't know what it is! > > Thanks in advance, > > Mike > > Michael Ashton, CFA > Managing Principal > > Enduring Investments LLC > W: 973.457.4602 > C: 551.655.8006 > Schedule a Call: https://calendly.com/m-ashton > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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. ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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.