Sum of vector in R

Asked

Viewed 649 times

2

I have a vector of integer values in R, for example:

y = c(rep(1:4, c(36,9,2,1)), 6, 6)

and I need to make a sum within a function, like this:

equation

that is, I need to do

36*funcao_f(1,phi)+9*funcao_f(2,phi)+...

considering, for example:

phi = 1

funcao_f = function(I,PHI)(I*(I-1))/(1+(I*PHI))

How do I do this in R, given a random y vector (which I don’t necessarily know how much of each generated value I have, but R will calculate the n_i for me, identifying i=1, or i = 2... in my y vector)?

Thanks a lot of people Good to R!!!

2 answers

0


The function funbelow calculates the sum of the question. One of the arguments is FUN, the function of I and of PHI, in the case of the question funcao_f.

fun <- function(I, PHI, FUN){
  tbl <- table(I)
  n <- as.integer(names(tbl))
  sum(n*FUN(tbl, PHI))
}

funcao_f <- function(I, PHI)(I*(I-1))/(1+(I*PHI))

y <- c(rep(1:4, c(36,9,2,1)), 6, 6)
phi <- 1

fun(y, phi, funcao_f)
#[1] 54.45405

0

Look, from what I understand, you can do everything vectorially anyway. R does vector operations element by element, so instead of making a function that has this behavior, transform the output of the funcao_f in a vector, there is only multiply with the vector that has the n_i.

If the entrance of funcao_f = function(I,PHI)(I*(I-1))/(1+(I*PHI)) are two vectors, or a vector and a scalar, the output will already be a vector. In case what you could do later would be.

resposta = y*funcao_f(I,phi)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.