Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9238599
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T07:47:58+00:00 2026-06-18T07:47:58+00:00

If I want to sample numbers to create a vector I do: set.seed(123) x

  • 0

If I want to sample numbers to create a vector I do:

set.seed(123)
x <- sample(1:100,200, replace = TRUE)
sum(x)
# [1] 10228

What if I want to sample 20 random numbers that sum to 100, and then 30 numbers but still sum to 100. This I imagine will be more of a challenge than it seems. ?sample and searching Google has not provided me with a clue. And a loop to sample then reject if not close enough( e.g. within 5) of the desired sum I guess may take some time.

Is there a better way to achieve this?

an example would be:

foo(10,100) # ten random numbers that sum to 100. (not including zeros)
# 10,10,20,7,8,9,4,10,2,20
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T07:47:59+00:00Added an answer on June 18, 2026 at 7:47 am

    Here’s another attempt. It doesn’t use sample, but uses runif. I’ve added an optional “message” to the output showing the sum, which can be triggered using the showSum argument. There is also a Tolerance argument that specifies how close to the target is required.

    SampleToSum <- function(Target = 100, VecLen = 10, 
                            InRange = 1:100, Tolerance = 2, 
                            showSum = TRUE) {
      Res <- vector()
      while ( TRUE ) {
        Res <- round(diff(c(0, sort(runif(VecLen - 1)), 1)) * Target)
        if ( all(Res > 0)  & 
             all(Res >= min(InRange)) &
             all(Res <= max(InRange)) &
             abs((sum(Res) - Target)) <= Tolerance ) { break }
      }
      if (isTRUE(showSum)) cat("Total = ", sum(Res), "\n")
      Res
    }
    

    Here are some examples.

    Notice the difference between the default setting and setting Tolerance = 0

    set.seed(1)
    SampleToSum()
    # Total =  101 
    #  [1] 20  6 11 20  6  3 24  1  4  6
    SampleToSum(Tolerance=0)
    # Total =  100 
    #  [1] 19 15  4 10  1 11  7 16  4 13
    

    You can verify this behavior by using replicate. Here’s the result of setting Tolerance = 0 and running the function 5 times.

    system.time(output <- replicate(5, SampleToSum(
      Target = 1376,
      VecLen = 13,
      InRange = 10:200,
      Tolerance = 0)))
    # Total =  1376 
    # Total =  1376 
    # Total =  1376 
    # Total =  1376 
    # Total =  1376 
    #    user  system elapsed 
    #   0.144   0.000   0.145
    output
    #       [,1] [,2] [,3] [,4] [,5]
    #  [1,]   29   46   11   43  171
    #  [2,]  103  161  113  195  197
    #  [3,]  145  134   91  131  147
    #  [4,]  154  173  138   19   17
    #  [5,]  197   62  173   11   87
    #  [6,]  101  142   87  173   99
    #  [7,]  168   61   97   40  121
    #  [8,]  140  121   99  135  117
    #  [9,]   46   78   31  200   79
    # [10,]  140  168  146   17   56
    # [11,]   21  146  117  182   85
    # [12,]   63   30  180  179   78
    # [13,]   69   54   93   51  122
    

    And the same for setting Tolerance = 5 and running the function 5 times.

    system.time(output <- replicate(5, SampleToSum(
      Target = 1376,
      VecLen = 13,
      InRange = 10:200,
      Tolerance = 5)))
    # Total =  1375 
    # Total =  1376 
    # Total =  1374 
    # Total =  1374 
    # Total =  1376 
    #    user  system elapsed 
    #   0.060   0.000   0.058 
    output
    #       [,1] [,2] [,3] [,4] [,5]
    #  [1,]   65  190  103   15   47
    #  [2,]  160   95   98  196  183
    #  [3,]  178  169  134   15   26
    #  [4,]   49   53  186   48   41
    #  [5,]  104   81  161  171  180
    #  [6,]   54  126   67  130  182
    #  [7,]   34  131   49  113   76
    #  [8,]   17   21  107   62   95
    #  [9,]  151  136  132  195  169
    # [10,]  194  187   91  163   22
    # [11,]   23   69   54   97   30
    # [12,]  190   14  134   43  150
    # [13,]  156  104   58  126  175
    

    Not surprisingly, setting the tolerance to 0 would make the function slower.


    Speed (Or lack thereof)

    Note that since this is a “random” process, it’s hard to guess how long it would take to find the right combination of numbers. For example, using set.seed(123), I ran the following test three times in a row:

    system.time(SampleToSum(Target = 1163,
                            VecLen = 15,
                            InRange = 50:150))
    

    The first run took just over 9 seconds. The second took just over 7.5 seconds. The third took… just under 381 seconds! That’s a lot of variation!

    Out of curiosity, I added a counter into the function, and the first run took 55026 attempts to arrive at a vector that satisfied all of our conditions! (I didn’t bother trying for the second and third attempts.)

    It might be good to add some error or sanity checking into the function to make sure the inputs are reasonable. For example, one should not be able to enter SampleToSum(Target = 100, VecLen = 10, InRange = 15:50) since with a range of 15 to 50, there’s no way to get to 100 AND have 10 values in your vector.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the vector d<-1:100 I want to sample k=3 times from this vector
I want to create a simple cipher in which it uses Phone numbers in
I need to create a function that will generate 2 random numbers between x
See the sample Timesten procedure below. CREATE OR REPLACE PROCEDURE test_proc(employee_id IN NUMBER) AS
I want to create a function in C. It will return a random integer
I want to create my own range of numbers in Java, and still be
I want to do something simple in assembly language. addition two numbers, and print
I want to write a map/reduce job to select a number of random samples
I want to sample data based on a timestamp field. I am reading huge
I have 600,000+ observed data that I want to sample proportional to its ZIP

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.