R语言中基于排序变量的状态变更:暴露人群状态更新的代码条件实现
Solution
First, let's clarify and correct some initial setup steps, then implement the conditional logic in your loop.
Step 1: Proper Initial Setup
First, define your initial data frame and the sum_exposed vector correctly (your original syntax for sum(exposed[i]) was invalid):
# Initial data frame df <- data.frame( i = 1:5, exposed = c("y", "y", "y", "n", "n"), index = c(22, 12, 6, 54, 3) ) t <- 5 # Total exposed individuals at each time point (t=1 to t=5) sum_exposed <- c(3, 4, 1, 4, 5) # Initialize evolution list evol <- list() for(i in 1:t){evol[[i]] <- df}
Step 2: Implement the Update Logic
Now, fill in the loop with conditional logic that handles both increasing and decreasing exposed counts:
for (i in 2:t) { # Get the previous time point's data prev_df <- evol[[i-1]] # Calculate the change in exposed count prev_sum <- sum_exposed[i-1] current_sum <- sum_exposed[i] delta <- current_sum - prev_sum # Make a copy of the previous data to modify new_df <- prev_df if (delta > 0) { # Case 1: Need to add delta exposed individuals # Get non-exposed individuals, sort by index descending, pick top delta non_exposed <- prev_df[prev_df$exposed == "n", ] non_exposed_sorted <- non_exposed[order(-non_exposed$index), ] to_convert <- non_exposed_sorted$i[1:delta] # Update their exposed status new_df$exposed[new_df$i %in% to_convert] <- "y" } else if (delta < 0) { # Case 2: Need to remove (-delta) exposed individuals num_to_convert <- -delta # Get exposed individuals, sort by index ascending, pick top num_to_convert exposed_ind <- prev_df[prev_df$exposed == "y", ] exposed_sorted <- exposed_ind[order(exposed_ind$index), ] to_convert <- exposed_sorted$i[1:num_to_convert] # Update their exposed status new_df$exposed[new_df$i %in% to_convert] <- "n" } # Save the updated data to the evolution list evol[[i]] <- new_df }
How It Works
Let's break down the logic to match your examples:
- From
evol[[1]]toevol[[2]]:sum_exposedincreases from 3 to 4 (delta=1). We take the non-exposed individual with the highest index (individual 4, index=54) and change their status to "y". - From
evol[[2]]toevol[[3]]:sum_exposeddecreases from 4 to 1 (delta=-3). We take the 3 exposed individuals with the lowest indices (individuals 3, 2, 1 with indices 6, 12, 22) and change their status to "n".
Verification
After running the code, you can check the results with:
# View evol[[2]] evol[[2]] # View evol[[3]] evol[[3]]
These will match the exact examples you provided.
内容的提问来源于stack exchange,提问作者Angelo_231
相关产品推荐
相关产品推荐

