R语言foreach循环仅执行最后一条语句,如何实现多语句执行?
Hey there! I see the issue you're running into—let's break this down and fix it quickly.
Why Only the Last Line Runs
In R, any code block (including the body of your foreach loop) automatically returns only the result of the final statement in the block. So when you run:
foreach (i=1:10) %dopar% { paste("Jimmy") paste("bobby") }
The first paste("Jimmy") executes, but its result is discarded immediately. The loop only captures the output of the last line, paste("bobby"), which is why your final list is full of "bobby" values.
How to Return Both Values
To get both "Jimmy" and "bobby" from each iteration, you need to package both results into a single object (like a vector, list, or data frame) and make that the final statement in your loop body. Here are a few common approaches:
1. Return as a Vector
If you want each list element to be a simple vector of both strings:
foreach (i=1:10) %dopar% { c(paste("Jimmy"), paste("bobby")) }
This will give you a list where each element is a length-2 vector containing "Jimmy" and "bobby".
2. Return as a Named List
For more readability, you can wrap the results in a named list:
foreach (i=1:10) %dopar% { list(first_name = paste("Jimmy"), last_name = paste("bobby")) }
Now each list element is a named list, making it easy to access individual values later (e.g., result[[1]]$first_name).
3. Store Intermediate Results First
If you need to run additional code before returning the results, store each value in a variable first, then package them:
foreach (i=1:10) %dopar% { # Run any intermediate steps here name1 <- paste("Jimmy") name2 <- paste("bobby") # Package and return both values c(name1, name2) }
Bonus: Combine Results into a Single Structure
If you want to aggregate all iterations into a single matrix or data frame instead of a list, use the .combine parameter:
# Combine into a matrix (each column is one iteration's results) foreach (i=1:10, .combine = cbind) %dopar% { c(paste("Jimmy"), paste("bobby")) } # Or combine into a data frame foreach (i=1:10, .combine = rbind) %dopar% { data.frame(name1 = paste("Jimmy"), name2 = paste("bobby")) }
The key takeaway is that foreach captures whatever the final statement in your loop body returns—so make sure that final statement includes all the values you want to keep!
内容的提问来源于stack exchange,提问作者Francis part 2

