Summarized Subscription Items

Idea:

Suppose I have lists with two vectors. Then I would like to take the first element of the first vector and divide it by the sum of it and the first element of the second vector of the list. Then do this for all items in the first list. After that, do the same, but with the second list vector.

List Code:

tau1 <- list(c(0.43742669 , 0.64024429,  0.39660069,  0.11849773), c(0.5060767, 0.4857891, 0.4553237, 0.5045598))

My processed code is for only two vectors.

 Tau1 <- vector('list', 2)
for(i in seq_along(tau1)){
  for(j in 1:length(tau1[[1]])){
    Tau1[[i]][[j]] <- tau1[[i]][[j]] / Reduce('+', tau1[[1]][[j]], tau1[[2]][[j]])

  }

}

Example:

The first element of the list:

TT1 <- tau1[[1]][[1]]/(tau1[[1]][[1]]+tau1[[2]][[1]])
 [1] 0.4636196

Then for the second list item:

 TT2 <- tau1[[2]][[1]]/(tau1[[1]][[1]]+tau1[[2]][[1]])
   [1] 0.5363804

Problem:

I would like to do this for an arbitrary number of vectors. For instance,

Reduce('+', tau1[[1]][[j]], tau1[[2]][[j]], tau1[[3]][[j]], tau1[[4]][[j]])

How can I do this automatically? any help please?

+4
source share
3 answers

Reduce, [[i]], list, a vector. "j'th index" "j- " tau1 [[i]] '

Tau1 <- vector('list', 2)
for(i in seq_along(tau1)){
  for(j in seq_along(tau1[[1]])){
    Tau1[[i]][[j]] <- tau1[[i]][[j]] /Reduce(`+`, tau1)[j]
      }

   }

, , , . NULL , NULL list. , "NULL". ,

tau1 <- list(c(0.43742669 , 0.64024429,  "NULL",  0.11849773), 
        c(0.5060767, 0.4857891, 0.4553237, 0.5045598))

f (init, x [[i]]):

+2

[[.

j -, sapply(tau1, "[[", j). , : sum(sapply(tau1, "[[", j))

PS.: for(j in 1:length(tau1[[1]]){} for(j in 1:length(tau1[[i]]){} - .

+2

Here is a basic single line R:

lapply(tau1, "/", do.call(mapply, c(FUN = sum, tau1)))

# [[1]]
# [1] 0.4636196 0.5685838 0.4655351 0.1901875
# 
# [[2]]
# [1] 0.5363804 0.4314162 0.5344649 0.8098125

Or alternatively (from @lmo's comment):

lapply(tau1, "/", Reduce("+", tau1))

Here is the equivalent purrr:

library(purrr)

tau1 %>% map(`/`, pmap_dbl(., sum))

# [[1]]
# [1] 0.4636196 0.5685838 0.4655351 0.1901875
# 
# [[2]]
# [1] 0.5363804 0.4314162 0.5344649 0.8098125
+2
source

Source: https://habr.com/ru/post/1688790/


All Articles