0

I have a problem. I want to express the formula

TCCI = 1 - (d-1) / Sigma from j=1 to d for (phi[j]-1) 

The Formula I want to write in R

This is my first Code:

TCCI = function(d,phi){
  for(j in 1:d){
    tcci <- 1 - (d-1 / sum(phi[j]-1))
    return(tcci)
  }
}

My second try:

TCCI2 = function(d,phi){
  my.sum = 0 
  for(j in 1:d){
    tcci <- 1 - (d-1 / sum(phi[j]-1))
    my.sum = my.sum + tcci
    return(my.sum)
  }
}

I have no idea if this would work for the summation sign. Thank you in advance!

svoxv
  • 11
  • 1
  • Welcome to StackOverflow. Do you have any example data that we can test the function with? It will be easier than only reading the code. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Harrison Jones Sep 22 '21 at 14:51
  • what do you expect as an output? a constant or a vector? would be good to provide a sample input and what you expect as an output – Macosso Sep 22 '21 at 15:02
  • I am expecting a constant. For instance if d = 2 and phi = 3 The answer should be 0.75. How do I write a summation formula with a constant such as phi = 3 ? :) – svoxv Sep 22 '21 at 15:20
  • If d and phi are both constants then you don't need `sum`. See my update below to the answer. – Harrison Jones Sep 22 '21 at 15:43
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 26 '21 at 13:07

1 Answers1

1

You shouldn't need a loop to perform this calculation. Functions in R will automatically perform a sum on a vector, with the sum function. Here is an example where I guessed what your data could look like.

d <- 200
phi <- 1:d
phi_range <- 180

1 - ((d - 1) / sum(phi[1:phi_range] - 1)) 
Harrison Jones
  • 2,256
  • 5
  • 27
  • 34
  • In my case phi is a constant. Do you have an idea how i could express this in another way ? – svoxv Sep 22 '21 at 15:27
  • I think I'm confused by the formula then. The formula says `phi_j` which implies that `phi` is not a constant but a vector. – Harrison Jones Sep 22 '21 at 15:40
  • Oh i think i made a mistake.. yeah phi_j is a vector and d is therefore a constant.. sorry. But how can I then assign a range of 1:5 to the vector phi according to your example. In my case the summation sign from j=1 to d for phi[j] represents the number of immediate parents for each component and d is the number of distinct component parts. I have to apologize I am a little confused. I have just started to program in R. – svoxv Sep 22 '21 at 16:46
  • In the formula you provided the range of the vector phi was equal to d, the same d that is in the numerator of the formula. Are you sure you want to set a different range for phi? If you do you can use the new code in my answer. You can select a range using `phi_range` which means it will only take the first `phi_range` values. In my code (just as an example) I'm taking the first 180 values from the `phi` vector. – Harrison Jones Sep 22 '21 at 20:57