Lapply returns an error: Error in FUN (X [[i]], ...): non-numeric argument for binary operator

Idea:

I have two lists, each of which contains two vectors. I would like to multiply the first element of the first vector by the first vector of the second list. Then take the average. The second problem is related to Reducethat return the same error.

Additional explanation:

Tautakes the first vector of the first element of the list. Then we divide it into the sum and the first vector of the second element of the list.

I.e:

Tau[[1]][[1]] <-xy[[1]][[1]] / xy[[1]][[1]]+xy[[2]][[1]]

Tau[[1]][[2]] <- xy[[1]][[2]] / xy[[1]][[2]]+xy[[2]][[2]]

Then:

Tau[[2]][[1]] <- xy[[2]][[1]] / xy[[1]][[1]]+xy[[2]][[1]]

Tau[[2]][[2]] <- xy[[2]][[2]] / xy[[1]][[2]]+xy[[2]][[2]]

Then it wtakes an average value for each of them.

I tried this:

Tau <- lapply(seq_along(tau), function(i) {
      lapply(seq_along(tau[[i]]), function(j) {
        tau[[i]][[j]] / Reduce("+", tau)[j]
      })
    })

but the same problem.

x <- list(rnorm(10, 0, 2), rnorm(10, 0, 3))
z <- list(rnorm(10, 1, 2), rnorm(10, 1, 3))
d <- list(x,z)
y <- list(c(0.5,0.6), c(0.4,0.3))

xy <- vector("list", 2)
    xy[[i]] <-  lapply(y,'*', d)

Error in FUN (X [[i]], ...): non-numeric argument for binary operator

This also does not work.

w <- Tau <- list()
 for(i in 1:2){
      for(j in 2){
     Tau[[i]] <- xy[[i]][[j]] /Reduce(`+`, tau)[j]
     w[[i]] <- mean(Tau[[i]][[j]])
}

Example:

y (, 0.5)

> d

0.5

[[1]]
[[1]][[1]]
 [1] -0.44040072 -1.69336471 -0.04573857 -3.74011962  3.30269244 -3.37658068  3.06804389  0.13188553
 [9]  3.71420040 -0.74085067

0.6 ( )

[[1]][[2]]
 [1] -1.6611338 -1.3624477 -1.4476909  0.6665619 -6.3073039 -2.8770249 -0.3958278 -4.6663914  1.1611647
[10]  2.1651238

0.4

[[2]]
[[2]][[1]]
 [1]  0.65857032  2.25298174  1.42681523  1.88253492  2.39446475 -2.91032026  1.39494374  0.07196944
 [9]  2.17966571 -1.06532219

0.3

[[2]][[2]]
 [1]  2.2861982 -1.3721936  2.3371474  2.8234391  4.2834482  5.7823569  4.7208008  0.7277582 -1.0594293
[10] -1.1606454

lapply, . , ?

+1
1

d y ( y, ), lapply. lapply s:

xy <- lapply(seq_along(d), function(i) {
  lapply(seq_along(d[[i]]), function(j) {
    d[[i]][[j]] * y[[i]][[j]]
  })
})

map2 purrr, .

library(purrr)
xy <- map2(d, y, ~ map2(.x, .y, `*`))

, , , , . purrr (, map2 ).

# multiply each item in d by corresponding number in y
xy <- map2(d, y, ~ map2(.x, .y, `*`))

# sum the first item in each list, then second item in each list
denominator <- map(transpose(xy), reduce, `+`)

# divide each item by the denominator
tau <- map(xy, ~ map2(., denominator, `/`))

# take the mean of each vector within each list
w <- map(tau, ~ map(., mean))
+2

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


All Articles