R append() function - Append elements
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 concatenating with c().
The syntax of the append() function is as follows:
append(x, values, after = length(x))
Parameter description:
xOriginal vector.
valuesThe element(s) to add.
afterInsert position (after which index), defaults to the end.
Example
x <- c(1, 2, 3, 4, 5)
# Append at the end
result1 <- append(x, c(6, 7))
print("Append at the end:")
print(result1)
# Insert after the specified position
result2 <- append(x, c(9, 9), after = 2)
print("Insert after the 2nd element:")
print(result2)
# Insert at the beginning (after = 0)
result3 <- append(x, 0, after = 0)
print("Insert at the beginning:")
print(result3)
# Append at the end
result1 <- append(x, c(6, 7))
print("Append at the end:")
print(result1)
# Insert after the specified position
result2 <- append(x, c(9, 9), after = 2)
print("Insert after the 2nd element:")
print(result2)
# Insert at the beginning (after = 0)
result3 <- append(x, 0, after = 0)
print("Insert at the beginning:")
print(result3)
The output after executing the above code is:
[1] "末尾追加:" [1] 1 2 3 4 5 6 7 [1] "在第 2 个元素后插入:" [1] 1 2 9 9 3 4 5 [1] "在开头插入:" [1] 0 1 2 3 4 5
append() is very useful when dynamically building vectors:
Example
# Dynamically collect data that meet the condition
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)
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)
The output after executing the above code is:
[1] "能被 3 整除的数:" [1] 3 6 9 12 15 18Other Extensions
R Language Examples