Understanding the effect of c () on named vectors

Why:

c(d = 1:3)

equal to the named vector, like:

d1 d2 d3 
1  2  3 

And where is this documented?

Help file c says:

## do *not* use
c(ll, d = 1:3) # which is == c(ll, as.list(c(d = 1:3))

but as.listis redundant (and the closing bracket is missing). And I don't think that means the behavior documentation above.

+4
source share
2 answers

This is a good observation that led me to a valid C code (since it c()is a primitive function). Just share your observation with the code.

Both in the actual C code functiondo_c() that does this c()for R, and inside this function there is a section devoted to assign attributes to the output.

/* Build and attach the names attribute for the returned object. */

    if (data.ans_nnames && data.ans_length > 0) {
    PROTECT(data.ans_names = allocVector(STRSXP, data.ans_length));
    data.ans_nnames = 0;
    while (args != R_NilValue) {
        struct NameData nameData;
        nameData.seqno = 0;
        nameData.count = 0;
        NewExtractNames(CAR(args), R_NilValue, TAG(args), recurse, &data, &nameData);
        args = CDR(args);
    }
    setAttrib(ans, R_NamesSymbol, data.ans_names);
    UNPROTECT(1);
    }

, NewExtractNames() - , , ,

/* NewExtractNames(v, base, tag, recurse):  For c() and  unlist().
 * On entry, "base" is the naming component we have acquired by
 * recursing down from above.
 *  If we have a list and we are recursing, we append a new tag component
 * to the base tag (either by using the list tags, or their offsets),
 * and then we do the recursion.
 *  If we have a vector, we just create the tags for each element. */

, , , , .

, .

+1

, use.names:

c(d = 1:3)
d1 d2 d3 
 1  2  3 
c(d = 1:3,use.names=F)
[1] 1 2 3

: https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/c

+1

Source: https://habr.com/ru/post/1693676/


All Articles