如何在R语言循环中使用get函数为向量追加新值?
How to Append Values to Vectors in a Loop Using
get() and assign() Great question! The assign() function does have that annoying quirk where it overwrites existing objects instead of appending to them. Luckily, pairing it with get() lets you safely update vectors by first grabbing their current state, adding your new values, then saving the updated version back.
Step-by-Step Example
First, let's set up our initial setup (with a fix to avoid overwriting right away):
set.seed(11) my_future_vectors <- c("vec1", "vec2", "vec3") # Initialize empty vectors if they don't exist yet for (vec_name in my_future_vectors) { if (!exists(vec_name)) { assign(vec_name, numeric(0)) # Start with an empty numeric vector } } # Now append values to each vector in a loop for (vec_name in my_future_vectors) { # Grab the current state of the vector current_values <- get(vec_name) # Add new values (here we're adding 3 random numbers between 0 and 1) updated_values <- c(current_values, runif(3, 0, 1)) # Save the updated vector back to its original name assign(vec_name, updated_values) }
Testing the Append Functionality
If you want to manually append a specific value (like 1 to vec1), you can do this without overwriting:
# Append 1 to vec1 assign("vec1", c(get("vec1"), 1)) # Check the result - vec1 will have its original 3 random numbers plus 1 vec1
Key Notes
- Initialize first: Starting with empty vectors ensures you don't get an error when trying to
get()a vector that hasn't been created yet. - Use
c()orappend(): Both work for combining existing and new values.append()is sometimes more readable if you want to specify where to add the new values (e.g.,append(current_values, new_values, after = length(current_values))). - Environment awareness: If you're working inside a function, make sure you specify the environment in
get()andassign()(using theenvirargument) to avoid accidentally modifying the global environment.
内容的提问来源于stack exchange,提问作者Alexandros
相关产品推荐
相关产品推荐

