R语言无需重复写变量名的原地赋值:时隔6年是否有新方案?
Great question—those repetitive variable name writes in R used to be such a pain, right? Let's break down how modern R (six years after your original question) handles the two scenarios you mentioned:
1. Incrementing a Numeric Variable (my_long_int_name <- my_long_int_name + 1)
Good news! As of R 4.3.0 (released in April 2023), native R now supports compound assignment operators, just like Python. You can now write this clean, concise line instead of repeating the variable name:
my_long_int_name += 1
This works for all basic arithmetic operations too: -= (subtract), *= (multiply), /= (divide), and even ^= (exponentiate). No more tedious repetition for these simple updates—finally!
2. Appending to a Vector (my_long_vector_var_name <- append(my_long_vector_var_name, new_var))
Base R still doesn't have a built-in in-place append operator, but you can tidy this up nicely with the magrittr assignment pipe (%<>%), which comes with the tidyverse ecosystem (or you can load just magrittr directly). Here's how it works:
# Load magrittr (or tidyverse, which includes it) library(magrittr) # Now you can write this instead of repeating the variable name my_long_vector_var_name %<>% append(new_var)
The %<>% pipe takes the left-hand variable, passes it to the right-hand function (here, append() with new_var), and automatically assigns the result back to the original variable. No more typing that long variable name twice.
If you want to stick strictly to base R without extra packages, you could write a tiny helper function—but be cautious: it uses <<- to modify variables in the parent environment, which can lead to unexpected behavior if not used carefully:
append_inplace <- function(x, value) { var_name <- deparse(substitute(x)) if (!exists(var_name, envir = parent.frame())) { stop("Variable doesn't exist in the parent environment") } assign(var_name, append(x, value), envir = parent.frame()) } # Use it like this: append_inplace(my_long_vector_var_name, new_var)
That said, the %<>% pipe is a cleaner, more idiomatic solution for most R users these days.
Quick Recap
- For numeric increments: Use
+=(requires R ≥ 4.3.0) - For vector appends: Use
%<>% append(new_var)(requires magrittr/tidyverse)
These updates make R code much cleaner and cut down on typos from repeating long variable names—huge improvement over the old days!
内容的提问来源于stack exchange,提问作者Thomas

