R语言中实现存储值向下移位一位的技术求助
Hey there! Let's figure out why your current code isn't working and fix it up. 😊
Why Your Current Code Fails
You're assigning values starting from NEWxrp14 <- NEWxrp15 and working your way down to NEWxrp1 <- NEWxrp2, which causes a problem: once you overwrite NEWxrp14 with NEWxrp15's value, every subsequent assignment uses that already-updated value instead of the original. By the end, all variables end up equal to the original NEWxrp15—not the shift you want.
Solution 1: Reverse the Assignment Order
To properly shift values downward, you need to start from the smallest index and move upward. This way, each assignment uses the original, unmodified value from the next variable in line.
Here's the corrected code:
# Shift original values downward one position NEWxrp1 <- NEWxrp2 NEWxrp2 <- NEWxrp3 NEWxrp3 <- NEWxrp4 # ... continue this pattern until ... NEWxrp14 <- NEWxrp15 # Generate the new value for NEWxrp15 NEWxrp15 <- your_formula_here() # Replace with your actual formula
Now NEWxrp1 will take the original NEWxrp2 value, NEWxrp2 takes original NEWxrp3, and so on—until NEWxrp14 gets the original NEWxrp15 value. Finally, NEWxrp15 gets its fresh computed value.
Solution 2: Use a Vector (Cleaner & More Scalable)
Writing 14 lines of assignment is tedious. Using a vector simplifies the shift to one line, and it's easier to maintain if you ever add/remove variables:
# Pack all your NEWxrp variables into a single vector xrp_values <- c(NEWxrp1, NEWxrp2, NEWxrp3, ..., NEWxrp15) # Shift values: first 14 positions take the original values from positions 2-15 xrp_values[1:14] <- xrp_values[2:15] # Generate the new value for the last position xrp_values[15] <- your_formula_here() # Replace with your actual formula # Optional: Assign the updated vector values back to individual variables NEWxrp1 <- xrp_values[1] NEWxrp2 <- xrp_values[2] # ... continue until ... NEWxrp15 <- xrp_values[15]
This method eliminates repetitive code and reduces the chance of missing an assignment line.
内容的提问来源于stack exchange,提问作者MrPotato

