Вот один из способов получения 100 значений, используя rexp
и for-l oop. Мы можем создать пустой вектор и сохранить результат в векторе на основе индексации.
# Set seed for reproducibility
set.seed(1234)
# Create an empty vector
result <- numeric()
# Use for loop to create values and save the results
for(i in 1:100){
result[[i]] <- rexp(n = 1, rate = 0.001)
}
# See the first six elements in the result
head(result)
# [1] 2501.758605 246.758883 6.581957 1742.746090 387.182584 89.949671
# Plot the histogram
hist(result)
![enter image description here](https://i.stack.imgur.com/rylAH.png)
Вот еще один способ создания 100 значений и используйте для -l oop. Мы можем использовать c
для многократного объединения результата с вектором. Тем не менее, обратите внимание, что этот метод медленнее, чем предыдущий, и поэтому предыдущий является предпочтительным способом использования -l oop для сохранения значений.
# Set seed for reproducibility
set.seed(1234)
# Create an empty vector
result2 <- numeric()
# Use for loop to create values and save the results
for(i in 1:100){
x <- rexp(n = 1, rate = 0.001)
result2 <- c(result, x)
}
# See the first six elements in the result2
head(result2)
# [1] 2501.758605 246.758883 6.581957 1742.746090 387.182584 89.949671
Наконец, важно отметить, что функция rexp
имеет аргумент n
, позволяющий нам напрямую генерировать 100 значений без использования for-l oop.
# Set seed for reproducibility
set.seed(1234)
# Generate 100 values
result3 <- rexp(n = 100, rate = 0.001)
# See the first six elements in the result3
head(result3)
# [1] 905.2344 932.1655 2296.7747 15.3926 264.8849 933.5238
![enter image description here](https://i.stack.imgur.com/Y8vL7.png)