here is the code for a simulation I'm trying to run:
n_draws <- 1000
black <- rep(0, n_draws)
hispanic <- rep(0, n_draws)
asian <- rep(0, n_draws)
white <- rep(0, n_draws)
cutoff <- c(0.05,0.1,0.25,1)
draws <- runif(n_draws,0,1)
for (i in draws){
if (draws[i] < cutoff[1]){
black[i] <- 1
} else if ((draws[i] >= cutoff[1]) & (draws[i] < cutoff[2])){
hispanic[i] <- 1
} else if ((draws[i] >= cutoff[2]) & (draws[i] < cutoff[3]){
asian[i] <- 1
} else {
white[i] <- 1
}
}
Basically, I want to add a 1 to the corresponding list, conditional on where that number falls in the range (0,1). I'm not sure why this is giving an error. Suggestions?
You're just missing a closing bracket just after cutoff[3], also used seq_along in my example as it's a bit nicer
for (i in seq_along(draws)){
if (draws[i] < cutoff[1]){
black[i] <- 1
} else if ((draws[i] >= cutoff[1]) & (draws[i] < cutoff[2])){
hispanic[i] <- 1
} else if ((draws[i] >= cutoff[2]) & (draws[i] < cutoff[3])){
asian[i] <- 1
} else {
white[i] <- 1
}
}
Related
I have the below existing code in R. The code prints the next immediate prime number. I want to consider inclusive of starting number
np <- function(x){
if (x==1L | x==2L) {return(2L)}
else {
temp <- x+1
test <- 2:x
while( any( (temp %% test) == 0 ) ){
temp <- temp+1
}
temp
} }
Eg.. np(7) returns 11. But expected output is 7.
Try the code below (following a similar idea in the answer here)
np <- function(x) {
p <- x
repeat {
if (p %in% c(2, 3) | all(p %% ceiling(sqrt(2:p)) != 0)) {
return(p)
}
p <- p + 1
}
}
and you will see
> np(2)
[1] 2
> np(3)
[1] 3
> np(4)
[1] 5
> np(5)
[1] 5
> np(7)
[1] 7
Maybe it's stupid but does this do the trip?
np <- function(x){
if (x==1L | x==2L) {return(2L)}
else {
x= x-1
temp <- x+1
test <- 2:x
while( any( (temp %% test) == 0 ) ){
temp <- temp+1
}
temp
} }
You are testing numbers above x only by calling temp <- x+1. Here is a version that should work with minimal changes to your code:
np <- function(x){
if (x==1L | x==2L) {return(2L)}
else {
temp <- x
test <- 2:(x - 1)
while( any( (temp %% test) == 0 ) ){
temp <- temp+1
}
temp
} }
My code is stuck in an infinite loop, with the stop sign occurring. I have read through it multiple times, can anyone help?
I am trying to run trials using samples of possession probabilities and the subsequent make probabilities for a basketball team. I am following along with a video and made sure each step was completed properly.
How can I tell where I am stuck in an infinite loop and how do I fix it?
mc_hoops_ex <- function(trials) {
prob_pos <- c(0.148, 0.544, 0.308, 0.256)
prob_2pm <- 0.524
prob_3pm <- 0.378
prob_ftm <- 0.761
prob_orb <- 0.319
a <- 1
pts_ct <- 0
while (a <= trials) {
pos_outcome <- sample(c(1:4), 1, prob = prob_pos)
if(pos_outcome == 2) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_2pm) {
pts_ct <- pts_ct + 2
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
}
if(pos_outcome == 3) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_3pm) {
pts_ct <- pts_ct + 3
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
if(pos_outcome == 4) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_ftm) {
pts_ct <- pts_ct + 1
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
a <- a + 1
print(pts_ct / trials)
print((pts_ct / trials) * 66.3)
}
This looks like R code, based on the syntax, <- assignment, and functions like c() and runif().
You have the following loop: while (a <= trials). This loop will continue running until the condition no longer holds. Since you initialize a <- 1, this loop will not stop unless (1) trials < 1, in which case the loop will not run a single time, or (2) a is incremented until a > trials.
We can see that the only time a is changed is near the bottom of the function: a <- a + 1. However, look closely at the braces. This increment is outside the while-loop, so it never occurs and the loop runs forever.
I'm not sure if this will produce the expected results, but a corrected version that does not have an infinite loop is given below.
mc_hoops_ex <- function(trials) {
prob_pos <- c(0.148, 0.544, 0.308, 0.256)
prob_2pm <- 0.524
prob_3pm <- 0.378
prob_ftm <- 0.761
prob_orb <- 0.319
a <- 1
pts_ct <- 0
while (a <= trials) {
pos_outcome <- sample(c(1:4), 1, prob = prob_pos)
if(pos_outcome == 2) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_2pm) {
pts_ct <- pts_ct + 2
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
# Removed the closing brace here
if(pos_outcome == 3) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_3pm) {
pts_ct <- pts_ct + 3
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
if(pos_outcome == 4) {
pos_end <- 0
while (pos_end < 1) {
shot_prob <- runif(1)
if(shot_prob <= prob_ftm) {
pts_ct <- pts_ct + 1
pos_end <- 1
}
else {
orb_prob <- runif(1)
if(orb_prob >= prob_orb)
pos_end <- 1
}
}
}
a <- a + 1
} # Added a closing brace here instead
print(pts_ct / trials)
print((pts_ct / trials) * 66.3)
}
I have recently created this code and I am struggling with my run time for my for-loops. If I try to run this code, R is seems to take forever and I am not sure where the mistake is:
Graph <- rbind(c(0,0.8,0,0.2,0.1),
c(0,0,0.7,0.6,0.1),
c(0,0,0,0,0.9),
c(0,0,0,0,0.2),
c(0,0,0,0,0))
AmountNodes<-5
Method<-"unweighted"
InfectedNodes<-c(1)
## Function Amount Excluded
SIR_algorithm<-function(Graph, AmountNodes, Method){
ResultMatrix <- rep(0, AmountNodes)
as.data.frame(ResultMatrix)
if (strcmp(Method,"unweighted")){
Graph <- sign(Graph)}
for (i in 1:AmountNodes){
InfectedNodes <- rep(AmountNodes, 0)
ExcludedNodes <- rep(AmountNodes, 0)
InfectedNodes <-c(1)} # Initial Infection, k=Columns, j=Rows
while(sum(InfectedNodes) > 0){
InfectedNodes_Reflection <- InfectedNodes
for (j in 1:nrow(Graph)){
if (Graph[j] == 1){
for (k in 1:ncol(Graph)){
if ((Graph[k,j] > 0 && (InfectedNodes[k][1]) == 0 && (ExcludedNodes[k][1]) == 0)){
RandomValue <- runif(1, max=1, min=0)
if (RandomValue < (Graph[k,j])){
InfectedNodes_Reflection[k] <- k == 1
} #End If-Function
} #End If-Function
} #End For-Function k
} #End If-Function
}} #End For-Function j
for (j in 1:AmountNodes){
if (InfectedNodes[j] == 1){
InfectedNodes[j] <- c(0)
InfectedNodes_Reflection[j] <- c(0)
ExcludedNodes[j] <- c(1)}} #End If-Function and for-function
InfectedNodes <- InfectedNodes_Reflection
ResultMatrix[i] <- ExcludedNodes
length(ResultMatrix) #check length for ResultMatrix
length(ExcludedNodes) #check length for ExcludedNodes
} #End While-Function
#End For-Function i
AmountExcluded <- sum(ResultMatrix)/AmountNodes
#Damage Values<- ResultMatrix * Damage Potential
} #End Function_total
SIR_algorithm(Graph=Graph,AmountNodes=5,Method="unweighted")
Can someone help me please?
The problem is located at the following lines:
...
while(sum(InfectedNodes) > 0){
print(sum(InfectedNodes))
InfectedNodes_Reflection <- InfectedNodes
...
sum(InfectedNodes) is constant and equals to 1. So the loop is infinite.
I've simulated a 1000 steps in a markov chain were there are in total 6 different states(0-5) and we started in state 5. With the bar plot we can we see how many times we are in each state.
However, what i want to know is how many times we went to state 5, when the step just before it was from state 1. Since we are in total 26 times in state 1, the answer would the most be 26. Is there a way to see how many times we were in state 1 prior to going to state 5?
spec_sim <- function(x){
u <- runif(1)
if(x==0){
if(u < 0.5){
y <- 3
} else {
y <- 5
}
} else if(x==1){
if(u<0.1){
y <- 0
} else if(u < 0.1 + 0.1){
y <- 1
} else if(u < 0.1 + 0.1 + 0.4){
y <- 3
} else {
y <- 5}
} else if(x==2){
if(u<0.2){
y <- 1
} else if(u < 0.2 + 0.2){
y <- 2
} else if(u < 0.2 + 0.2 + 0.3){
y <- 3
} else {
y <- 5
}
} else if(x==3){
if(u<0.3){
y <- 2
} else if(u < 0.3 + 0.5){
y <- 3
} else{
y <- 5
}
} else if(x==4){
if(u<0.4){
y <- 3
} else {
y <- 4
}
} else if(x==5){
if(u<0.4){
y <- 4
} else {
y <- 5
}
}
return(y)
}
set.seed(1)
results <- numeric(1001)
for(i in 2:length(results)){
results[i]<- spec_sim(results[i - 1])
}
results <- results[-1]
barplot(table(results), xlab="states", ylab="frequency",
main="1000 simuleringar av en Markovkedja")
table(results)
Thank you for putting time into my question.
Your code did not run for me, but here is an example that does what you ask:
library(dplyr)
df <- data.frame(state=c(1,5,3,5,4,5,2,5,2,1,5))
df <- mutate(df, state_diff= state - lag(state))
which(df$state==5 & df$state_diff == 4)
length(which(df$state==5 & df$state_diff == 4))
EDIT:
This should now work with your fixed code:
df <- data.frame(results)
df<- mutate(df, results_diff = results - lag(results))
length(which(df$results==5 & df$results_diff == 4))
which(df$results==5 & df$results_diff == 4)
There is another way in base R, too:
length(which(diff(results) == 4))
Very easy to understand and without knowledge of dplyr
Explanation:
Function diff() calculates the difference between the elements of a vector. If your results go from state 1 to state 5, the difference between the two elements is +4. So you are searching the elements, where the difference is +4. With which you get the number of the index of diff(results) == 4. And with length you can count the indices. So you get the number of changes from 1 to 5. Note that you do not get the changes from 5 to 1, because then the result is -4.
Regards,
J_F
I have generated an infinite loop and don't know how to fix it.
I essentially want to go through the data frame rnumbers and generate rstate2 with 1, -1, or 0 depending on what is in rnumbers
The function step_generator is getting stuck at the repeat function. I am not sure how to make the code put -1 in rstate2 if rnumber is less than C and then repeat an ifelse function for the next rows until a value of D or greater is obtained. Once D is obtained exit the repeat function and go back into the original for loop.
Here is my code:
rnumbers <- data.frame(replicate(5,runif(20000, 0, 1)))
dt <- c(.01)
A <- .01
B <- .0025
C <- .0003
D <- .003
E <- .05
rstate <- rnumbers # copy the structure
rstate[] <- NA # preserve structure with NA's
# Init:
rstate[1, ] <- c(0)
step_generator <- function(col, rnum){
for (i in 2:length(col) ){
if( rnum[i] < C) {
col[i] <- -1
repeat {
ifelse(rnum[i] < E, -1, if(rnum[i] >= D) {break})
}
}
else { if (rnum[i] < B) {col[i] <- -1 }
else {ifelse(rnum[i] < A, 1, 0) } }
}
return(col)
}
# Run for each column index:
for(cl in 1:5){ rstate[ , cl] <-
step_generator(rstate[,cl], rnumbers[,cl]) }
Thanks for any help.
The problem is that you are not increasing i inside repeat loop, so basically you are testing the same i all the time, and because rnum[i] < C (from if condition) it will always be rnum[i] < E since C < E, and loop never breaks.
However, if you increase i inside repeat it still will come back to value resulting from for loop, so you have to do it in different way, for example using while loop. I'm not exactly sure if I understand what you are trying to do, but basing on your description I've made this function:
step_generator <- function(col, rnum){
i <- 2
while (i <= length(col)){
if (rnum[i] < C) {
col[i] <- -1
while ((i < length(col)) & (rnum[i + 1] < D)){
i <- i + 1
col[i] <- -1
}
} else if (rnum[i] < B){
col[i] <- -1
} else if (rnum[i] < A){
col[i] <- 1
} else {
col [i] <- 0
}
i <- i + 1
}
return(col)
}