On 2010-12-10 02:41, Amelia Vettori wrote:
two OutputsHello!
I am Amelia from Auckland and work for a bank. I am new to R and I have started
my venture with R just a couple of weeks back and this is my first mail to
R-forum. I need following assistance
Suppose my R code generates following outputs as
X
[[1]]
[1] 40
[[2]]
[1] 80 160
[[3]]
[1] 160 80 400
Y
[[1]]
[1] 10
[[2]]
[1] 10 30
[[3]]
[1] 5 18 20
and suppose
Z = c(1, 2, 3)
I need to perform the calculation where I will be multiplying corresponding
terms of X and Y individually and multiplying their sum by Z and store these
results in a dataframe.
I.e. I need to calculate
(40*10) * 1 # (first element of X + First
element of Y) * Z[1] = 400
((80*10)+(160*30)) * 2 # 2 row of X and 2nd row of Y = 11200
((160*5)+(80*18)+(400*20)) * 3 # 3rd row of X and 3 row of Y and Z[3] =
30720
So the final output should be
400
11200
30720
One way of doing it is write R code for individual rows and
arrive at the result e.g.
([[X]][1]*[[Y]][1])*1 will result in 400. However, I was just trying to know
some smart way of doing it as there could be number of rows and writing code
for each row will be a cumbersome job. So is there any better way to do it?
Please guide me.
Why not just write a function to do what
you've done by hand:
f <- function(x, y, z){
len <- length(x)
res <- rep(NA, len)
for(i in 1:len){
res[i] <- sum(x[[i]] * y[[i]]) * z[i]
}
res
}
f(X, Y, Z)
Peter Ehlers
I thank you in advance.
Thanking
all
Amelia
______________________________________________
R-help@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.