 # R code error in lenght of time

Please, can someone shed some light to what is wrong with my code? I am getting an error message
Error in t_store[count_times] <- cumsum(y_store)[length(y_store)] :
replacement has length zero

I am trying to get a sequence of times intervals using the lambda for a Uniform distribution.

Many Thanks

``````Question4 = function(lambda) {
# store each time generated by rexp
y_store = c()
# store the time of each patient
t_store = c(1)

# count the index of vector above
count_times = 1
# Loop of the Time until it exceeds 12
while (t_store[length(t_store)] <= 12) {
# Generate time to follow exp randomly
arrivals = dunif(rexp(0.1, lambda))
# store the each time generated by rexp
y_store[count_times] = arrivals
# Store the time for each patient's arrival
t_store[count_times] = cumsum(y_store)[length(y_store)]
# Index to next element in vector
count_times = count_times + 1

}
# Return the time stored for each patient
return (t_store)

}

main_Question4 = function() {
lambda = 10
# Get the arrival time
arr_times = Question4(10)
# Get the number of the people
num_Peo = (1:length(arr_times))

#Plot the of the time of the patients
plot(
num_Peo,
arr_times ,
main = 'Arrival Times',
xlab = 'The i-th Patient',
ylab = 'Arrival Time of The i-th Patient ',
col = 'red'
)

}

main_Question4()
``````

Hi @user124578. The problem due to `rexp` function. You may shift the two arguments.

``````Question4 = function(lambda) {
# store each time generated by rexp
y_store = c()
# store the time of each patient
t_store = c(1)

# count the index of vector above
count_times = 1
# Loop of the Time until it exceeds 12
while (t_store[length(t_store)] <= 12) {
# Generate time to follow exp randomly
arrivals = dunif(rexp(lambda, 0.1))
# store the each time generated by rexp
y_store[count_times] = arrivals
# Store the time for each patient's arrival
t_store[count_times] = cumsum(y_store)[length(y_store)]
# Index to next element in vector
count_times = count_times + 1

}
# Return the time stored for each patient
return (t_store)

}

main_Question4 = function() {
lambda = 10
# Get the arrival time
arr_times = Question4(10)
# Get the number of the people
num_Peo = (1:length(arr_times))

#Plot the of the time of the patients
plot(
num_Peo,
arr_times ,
main = 'Arrival Times',
xlab = 'The i-th Patient',
ylab = 'Arrival Time of The i-th Patient ',
col = 'red'
)

}

main_Question4()

`````` Created on 2019-10-09 by the reprex package (v0.3.0)

2 Likes

Thanks very much for your help

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.