R Func Append
# R append() Function - Add Elements
[ R Language Examples](https://example.com/r/r-examples.html)
The R append() function is used to insert elements into a vector.
append() can insert new elements at a specified position in a vector, which is more flexible than directly using c() concatenation.
The syntax of the append() function is as follows:
append(x, values, after = length(x))
**Parameter Description:**
* **x**: The original vector.
* **values**: The elements to add.
* **after**: The insertion position (after which index), default is at the end.
## Example
x <-c(1, 2, 3, 4, 5)
# Append at the end
result1 <-append(x, c(6, 7))
print("Append at end:")
print(result1)
# Insert after specified position
result2 <-append(x, c(9, 9), after =2)
print("Insert after 2nd element:");
print(result2)
# Insert at the beginning (after = 0)
result3 <-append(x, 0, after =0)
print("Insert at beginning:");
print(result3)
Executing the above code outputs the following result:
"Append at end:" 1 2 3 4 5 6 7 "Insert after 2nd element:" 1 2 9 9 3 4 5 "Insert at beginning:" 0 1 2 3 4 5
append() is very useful when dynamically building vectors:
## Example
# Dynamically collect data that meets conditions
all_numbers <-1:20
result <-c()# Empty vector
for(num in all_numbers){
if(num %%3==0){## Divisible by 3
result <-append(result, num)
}
}
print("Numbers divisible by 3:");
print(result)
Executing the above code outputs the following result:
"Numbers divisible by 3:" 3 6 9 12 15 18
[ R Language Examples](https://example.com/r/r-examples.html)
YouTip