Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating vectors, append() vs c()

Tags:

r

When concatenating two vectors, a and b, in R, it seems to me that

append(a,b)

and

c(a,b)

produces the same result. Are there any cases where one of the functions should be preferred over the other? Is append() meant for operations on lists rather than vectors?

like image 587
poplitea Avatar asked Sep 02 '20 18:09

poplitea


People also ask

How to concatenate a vector?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.

Which of the following function is used to combine more than one vector?

Explanation: When you want to create a vector with more than one element, you should use c() function which means to combine the elements into a vector.

Can you append to a vector?

Appending to a vector means adding one or more elements at the back of the vector. The C++ vector has member functions. The member functions that can be used for appending are: push_back(), insert() and emplace(). The official function to be used to append is push_back().

How do I append to a list in R?

To append an element in the R List, use the append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.


1 Answers

Take a look at the append() function. Basically it is the addition of the after argument that sets it apart. In general, c() will be more efficient since it skips this little bit of logic.

function (x, values, after = length(x)) 
{
    lengx <- length(x)
    if (!after) 
        c(values, x)
    else if (after >= lengx) 
        c(x, values)
    else c(x[1L:after], values, x[(after + 1L):lengx])
}
like image 183
Adam Avatar answered Sep 21 '22 14:09

Adam