[R] maximum value replacement

Bert Gunter gunter.berton at gene.com
Tue Oct 29 17:09:13 CET 2013


... and while I'm being OCD, note that the which() call in my code can
and should be omitted. It's completely superfluous. :-(

-- Bert



On Tue, Oct 29, 2013 at 8:46 AM, eliza botto <eliza_botto at hotmail.com> wrote:
> Thanks bert!!!
> it worked out perfectly well.
> thankyou onceagain,
>
> Eliza
>
>> Date: Tue, 29 Oct 2013 08:30:13 -0700
>> Subject: Re: [R] maximum value replacement
>> From: gunter.berton at gene.com
>> To: smartpink111 at yahoo.com; eliza_botto at hotmail.com
>> CC: r-help at r-project.org
>>
>> To Eliza: What if the max in a column is not unique?
>>
>> Given the small size of A, the solution given by Arun seems completely
>> adequate. However, I was wondering if it could be done without the
>> R-level loop in sapply by taking advantage of pmax() . Of course it
>> can. Here's code to illustrate how:
>>
>> A<- matrix(sample(15),nr=3)
>> A
>> B <- matrix(0,nr=1,nc=5)
>> m <- do.call(pmax,data.frame(t(A)))
>> d <- dim(A)
>> A[which(A==matrix(m,nr=d[1],nc=d[2],byrow=TRUE))] <- B
>> A
>>
>> Note that:
>>
>> 1. This does not generalize to functions other than max or min, afaik.
>> 2. I don't even know if it would be faster for large data, because the
>> data.frame call may slow things down.
>>
>> But it is fully vectorized (I think). So for illustration only, maybe...
>>
>> Cheers,
>> Bert
>>
>>
>>
>> On Tue, Oct 29, 2013 at 7:27 AM, arun <smartpink111 at yahoo.com> wrote:
>> > Hi,
>> > Try:
>> > sapply(seq_len(ncol(A)),function(i) {indx <- which(A[,i]%in%
>> > max(A[,i])); A[,i][indx] <- B[,i]; A[,i]})
>> >
>> > A.K.
>> >
>> >
>> >
>> >
>> > On Tuesday, October 29, 2013 10:16 AM, eliza botto
>> > <eliza_botto at hotmail.com> wrote:
>> > Dear Users,
>> > I have two matrices, one with 12 rows and 124 columns(A) and the other
>> > with 1 row and 124 column(B). i want to replace the maximum value in all
>> > columns of A with each (single) column value of B.
>> > How can i do it??
>> > Thanks indeed in advance,
>> >
>> > Eliza
>> > [[alternative HTML version deleted]]
>> >
>> > ______________________________________________
>> > 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.
>> >
>> >
>> > ______________________________________________
>> > 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.
>>
>>
>>
>> --
>>
>> Bert Gunter
>> Genentech Nonclinical Biostatistics
>>
>> (650) 467-7374



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

(650) 467-7374



More information about the R-help mailing list