简体   繁体   中英

R sum of random numbers?

I am trying to Write a R function that will generate n(that are passed to a function) random numbers and return the sum of the numbers and show that random set of numbers

I am new to R and assuming an array would be used here,but not sure. Also, my attempt only allows for 10 numbers, but if i try to do it for any amount other than 10 it gives wrong sum.

I don't know what I am doing wrong, but this is what i have got so far.

random.sum <- function(n) {  
x[1:n] <- ceiling(10*runif(n)) 
cat("x:", x[1:n], "\n") 
return(sum(x)) 
}
x <- rep(100, 10)
show(random.sum(10))

You are almost correct.

You don't need to assign x to anything outside the function, and inside your function you don't need to subset x , you can just assign it with the n random numbers. Then it will work

random.sum <- function(n) {
    x <- ceiling(10*runif(n)) 
    cat("x:", x, "\n")
    return(sum(x))
    }

random.sum(13)
x: 4 6 10 4 6 10 8 2 5 10 4 4 6 
[1] 79

Explanation

If you assign x <- rep(100, 10) outside the function, you are creating a vector size 10, each element being value 100.

Due to 'lexical scoping', this x is available inside the random.sum function, so when you have the line

x[1:4] <- ceiling(10*runif(n))   ## where n = 4

You are assigning the first 4 values of x to be a random number, but the remaining values are still 100. So your sum is actually (100 * 6) + 4 random numbers

You can see this happening if you throw in a few print statements into your original function

random.sum <- function(n) {
    print(x)
    x[1:n] <- ceiling(10*runif(n)) 
    print(x)
    cat("x:", x[1:n], "\n")
    print(x)
    return(sum(x))
} 

x <- rep(100, 10)
random.sum(4)

# [1] 100 100 100 100 100 100 100 100 100 100
# [1]   5   2   1   3 100 100 100 100 100 100
# x: 5 2 1 3 
# [1]   5   2   1   3 100 100 100 100 100 100
# [1] 611

How about something like this:

random.sum <- function(n) {
  # Store n random integers between 0 and 100 in vector called random_nums
  random_nums <- floor(runif(n, min=0, max=100))

  # Show the random numbers
  print(random_nums)

  # Return the sum of the random numbers
  return(sum(random_nums))
}

print(paste("Sum:", random.sum(5), sep=" "))

Example Output

[1] 57  3 64 18 46
[1] "Sum: 188"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM