in R, create a vector rounding function so that the coordinates vanish 100

Asked

Viewed 1,398 times

3

I have a vector of percentages, for example,

v<- c(32.5 , 43.2 , 24.1)
> round(v)
[1] 32 43 24
> sum(round(v))
[1] 99

I want a function that manipulates my surroundings so that it adds up to 100. In other words, I want a function fun so that sum(fun(v))=100. The criterion, of course, has to be so that each coordinate of fun(v) move as little as possible away from the original values. Anyone knows any method to do this?

  • 1

    http://stackoverflow.com/questions/792460/how-to-round-floats-to-integers-while-preserving-their-sum

3 answers

2


I believe that’s what you’re looking for:

x1=32.5
x2=43.2
if (x1-trunc(x1)>=.5) {y1=trunc(x1)+1} else y1=trunc(x1)
if (x2-trunc(x2)>=.5) {y2=trunc(x2)+1} else y2=trunc(x2)
y3=100-(y1+y2)
v=c(y1,y2,y3)
v
sum(v)

0

Have a look at the functions floor and ceiling? I already needed it that you’re behind I’d do something like that:

> v<- c(32.5 , 43.2 , 24.1)
> v
[1] 32.5 43.2 24.1
> sum(v)
[1] 99.8
> ceiling(sum(v))
[1] 100

You can vary the application of Ceiling and use the floor in the sum, there are several ways to do this. Even with the round and other R base rounding function:

ceiling(x)
floor(x)
trunc(x, ...)
round(x, digits = 0)
signif(x, digits = 6) 
  • I don’t think I was very clear in my question, but I want a fun function that gives me every v coordinate without decimal places and that when adding me to 100, that is sum(fun(v)) = 100. I have already arranged my question. Even so, I do not know this package and I will see if it gives to do something

  • @Vasco now understood, this is a "simple" optimization problem. Where v has the variables and 100 would be the already determined value of the objective function, so no time now but then I make an example for you. In excel using Solver it is very simple to do this.

  • thank you very much.. I prefer a code R. I never messed with optimization in R.

0

I do not believe that there is an objective (nonsubjective) way to do this. Imagine the following scenario:

> v <- c(rep(10.1, 9), 9.1)
> sum(v)
[1] 100
> sum(round(v))
[1] 99

What value of the vector round(v) you would change to sum(round(v)) be equal to 100?

The best solution would be to use the figures without rounding. If it is not possible, based on what you think reasonable, manually check which number should be changed or create a function that does this.

  • Perhaps by measuring the distances between their roundness of one and zero decimal places. Do some sort of minimizing these differences.

  • A minimizing would solve some cases, but I don’t think it would solve all of them. In the above case, for example, I couldn’t think of anything. How would you minimize?

  • Here is a method http://en.wikipedia.org/wiki/Largest_remainder_method

Browser other questions tagged

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