[R] Adding numbers in Outputs
jim holtman
jholtman at gmail.com
Fri Dec 10 14:43:37 CET 2010
try this:
> x <- list(40, c(80,160), c(160,80,400))
> y <- list(10, c(10,30), c(5,18,20))
> z <- c(1,2,3)
> mapply(function(a1,a2,a3){
+ a3 * sum(a1 * a2)
+ }
+ , x
+ , y
+ , z
+ )
[1] 400 11200 30720
On Fri, Dec 10, 2010 at 5:41 AM, Amelia Vettori
<amelia_vettori at yahoo.co.nz> 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.
>
> I thank you in advance.
>
> Thanking
> all
>
> Amelia
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> [[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.
>
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list