[R] Element-by-element operation (adding)
Steven Yen
syen04 at gmail.com
Mon May 23 07:39:17 CEST 2016
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]]
More information about the R-help
mailing list