user7905871
user7905871

Reputation:

How to divide each item of a list by a specific sum of two items from different list

Suppose I have lists such this:

x <- list(rnorm(10, 0, 2), rnorm(10, 0, 3))
z <- list(rnorm(10, 1, 2), rnorm(10, 1, 3))
d <- list(x,z)

Then, I would like to sum the first vector of the first list with the first vector of the second list. And the second vector of the first list with the second vector of the second list. That is, I would like to sum the corresponding vectors. The first of the first list with the first of the second and so on. Then, divide the first vector of the first list by the first some. The same for the first vector of the second list and so on.

y1 <- d[[1]][[1]]+d[[2]][[1]]
y2 <– d[[1]][[2]]+d[[2]][[2]]

Then, I would like to divide the first vector of the first list by the first sum. The same for the first vector of the second list. Then divide the second vector of each list by the second sum. Such this:

d[[1]][[1]]/y1
d[[1]][[2]]/y2
d[[2]][[1]]/y1
d[[2]][[2]]/y2

I can do this manually, however, how could I do this for arbitrary number of element of the list. That is, suppose I have 2 list each with 10 vectors.

Any help, please?

Upvotes: 1

Views: 339

Answers (1)

akrun
akrun

Reputation: 887213

One option would be to use reduce after transpose

library(tidyverse)
d %>%
    transpose %>%
    map(~ .x %>% reduce(`+`))

For the second part, extend the above

out <- d %>% 
       transpose %>% 
       map(~ .x %>% reduce(`+`)) %>% #get the sum
       replicate(length(d), ., simplify = FALSE) %>% #replicate to make lengths same
       map2(d, ., ~ map2(.x, .y, `/`)) #loop through the nested elements and divide

identical(out[[1]][[1]],  d[[1]][[1]]/y1)
#[1] TRUE

identical(out[[1]][[2]],  d[[1]][[2]]/y2)
#[1] TRUE

Upvotes: 1

Related Questions