Reputation: 113
I want to make a function k(n) that draws 'n' times from set {0,1,2,3,4,5,6,7,8,9,10} (the same probability for each one) and then it writes to each number if this is numbers is odd or even. For example :
k(3) draws numbers 1,6,8 and then my function print that :
1 is odd
6 is even
8 is even
My work so far :
About checking odd-even numbers function :
k=function(x)
if((x %% 2) == 0) {
print(paste(x,"is Even"))
} else {
print(paste(x,"is Odd"))
}
And I have the following idea for the next problems : I will draw n times from set {0,1,2,3,4,5,6,7,8,9,10} getting a list with a length of n. Then i will use sapply function for that list.
But i have a problem with drawing n times from above set. Can you please help me with that problem and can you mention please if my idea is correct ?
Upvotes: 1
Views: 57
Reputation: 11076
You do not show what the problem is or how you are drawing the random numbers, but I'll guess that you are using sample()
. Read the manual page for the function. The default behavior is selection WITHOUT REPLACEMENT, e.g:
sample(1:5, 5)
# [1] 2 5 3 1 4
sample(1:5, 6)
Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE'
You need to draw your samples with replacement, e.g.:
set <- 0:10
set.seed(42)
x <- sample(set, 5, replace=TRUE)
OE <- ifelse(x %% 2 == 0, "Even", "Odd")
cat("\n", paste(x, "is", OE, "\n"))
#
# 0 is Even
# 4 is Even
# 0 is Even
# 8 is Even
# 9 is Odd
Note that now 0 appears twice. Since it set the random number seed to 42 you should get the same values shown here.
Upvotes: 1