Skip to content
Back to formatted view

Raw Message

Message-ID: <71b53a06-7c85-b970-eaf8-b83f0d660ab7@gmail.com>
Date: 2016-05-23T05:39:17Z
From: Steven Yen
Subject: Element-by-element operation (adding)

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


	[[alternative HTML version deleted]]