Skip to content

Element-by-element operation (adding)

3 messages · Steven Yen, Peter Langfelder, Peter Dalgaard

#
Hi all, need help below. Thank you.

 > # Matrix v is 5 x 3
 > # Vector b is of length 3
 > # I like to add b[1] to all element in v[,1]
 > # I like to add b[2] to all element in v[,2]
 > # I like to add b[3] to all element in v[,3]
 > # as follows
 > v<-matrix(0,nrow=5,ncol=3); v
      [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    0    0    0
[5,]    0    0    0
 > b<-c(0.1,0.2,0.3)
 > cbind(
+ (b[1]+v[,1]),
+ (b[2]+v[,2]),
+ (b[3]+v[,3]))
      [,1] [,2] [,3]
[1,]  0.1  0.2  0.3
[2,]  0.1  0.2  0.3
[3,]  0.1  0.2  0.3
[4,]  0.1  0.2  0.3
[5,]  0.1  0.2  0.3
 > # I am obviously not using sapply correctly:
 > as.data.frame(sapply(b,"+",v))
     V1  V2  V3
1  0.1 0.2 0.3
2  0.1 0.2 0.3
3  0.1 0.2 0.3
4  0.1 0.2 0.3
5  0.1 0.2 0.3
6  0.1 0.2 0.3
7  0.1 0.2 0.3
8  0.1 0.2 0.3
9  0.1 0.2 0.3
10 0.1 0.2 0.3
11 0.1 0.2 0.3
12 0.1 0.2 0.3
13 0.1 0.2 0.3
14 0.1 0.2 0.3
15 0.1 0.2 0.3
#
Two solutions...

v + matrix(b, nrow(v), ncol(v), byrow = TRUE)

or

t(apply(v, 1, `+`, b))

Peter
On Sun, May 22, 2016 at 10:39 PM, Steven Yen <syen04 at gmail.com> wrote:
#
Or, as you're messing with transposes anyways, use the fact that the column-wise counterpart is automagically handled by recycling:

t(t(v)+b)

Or, look Ma, no transposes
 
v + rep(b, each=nrow(v))

(_always_ doublecheck the logic when you apply these and similar techniques! I have seen my share of student code where recycling had been applied along the wrong dimension of a matrix...)