Sachinthaka Abeywardana
2013-May-02 06:28 UTC
[R] Divide matrix columns by different numbers
Hi all, I have a feeling the most efficient way to do the following is to use apply, but I'm still wrapping my head around the function. k=matrix(1:6,nrow=3) div=1:2 Questions is how do I get R to divide the first column by 1 (div[1]) and the second column by 2 (div[2]) k/div treats k as a vector and does the following (not what I want)>k/div[,1] [,2] [1,] 1 2 [2,] 1 5 [3,] 3 3 Thanks, Sachin [[alternative HTML version deleted]]
On 02-05-2013, at 08:28, Sachinthaka Abeywardana <sachin.abeywardana at gmail.com> wrote:> Hi all, > > I have a feeling the most efficient way to do the following is to use > apply, but I'm still wrapping my head around the function. > > k=matrix(1:6,nrow=3) > > div=1:2 > > > Questions is how do I get R to divide the first column by 1 (div[1]) and > the second column by 2 (div[2]) > > k/div treats k as a vector and does the following (not what I want) > >> k/div > > > [,1] [,2] > [1,] 1 2 > [2,] 1 5 > [3,] 3 3k / rep(div,each=nrow(k)) Berend
Hi, ?sweep Regards, Pascal On 05/02/2013 03:28 PM, Sachinthaka Abeywardana wrote:> Hi all, > > I have a feeling the most efficient way to do the following is to use > apply, but I'm still wrapping my head around the function. > > k=matrix(1:6,nrow=3) > > div=1:2 > > > Questions is how do I get R to divide the first column by 1 (div[1]) and > the second column by 2 (div[2]) > > k/div treats k as a vector and does the following (not what I want) > >> k/div > > > [,1] [,2] > [1,] 1 2 > [2,] 1 5 > [3,] 3 3 > > > > Thanks, > Sachin > > [[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. >
? t(t(k)/div) #???? [,1] [,2] #[1,]??? 1? 2.0 #[2,]??? 2? 2.5 #[3,]??? 3? 3.0 A.K. ----- Original Message ----- From: Sachinthaka Abeywardana <sachin.abeywardana at gmail.com> To: "r-help at r-project.org" <r-help at r-project.org> Cc: Sent: Thursday, May 2, 2013 2:28 AM Subject: [R] Divide matrix columns by different numbers Hi all, I have a feeling the most efficient way to do the following is to use apply, but I'm still wrapping my head around the function. k=matrix(1:6,nrow=3) div=1:2 Questions is how do I get R to divide the first column by 1 (div[1]) and the second column by 2 (div[2]) k/div treats k as a vector and does the following (not what I want)>k/div? ? ? [,1] [,2] [1,]? ? 1? ? 2 [2,]? ? 1? ? 5 [3,]? ? 3? ? 3 Thanks, Sachin ??? [[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.