This is a convenience function that sets the names of an object and returns
it including the new names. It is most useful at the end of a function
definition where one is creating the object to be returned and would prefer
not to store it under a name just that the names can be assigned. In
addition to the function setNames() in base R the user can
decide, whether rownames, colnames or simply the names are to be set.
Arguments
- x
an object for which a names attribute will be meaningful.
- ...
the names to be assigned to the object. This should be a character vector of names named
dimnames,rownames,colnamesornames. Settingrownames=NULLwould remove existing rownames. All kind of names can be changed at the same time. Default would benames. Abbreviations are supported.
Details
A name of length one is recycled to the required extent, which is handy for
blanking out names with "". Names of any other length must match the
extent of the object exactly; a deviating length is reported as an error
rather than being recycled silently, as an unexpected length is almost
always a miscalculation upstream and duplicated names are hard to debug
later on.
See also
Other label.attrs:
label(),
renameX(),
setAttr-removeAttr-keepAttr
Examples
setNamesX(1:5, names=letters[1:5])
#> a b c d e
#> 1 2 3 4 5
# the default, if no argument names are provided, is "names"
setNamesX(1:5, letters[1:5])
#> a b c d e
#> 1 2 3 4 5
# rownames and columnnames can be set at the same time
setNamesX(matrix(c(1:12), nrow=4),
rownames=LETTERS[11:14], colnames=c("perc", "lci", "uci"))
#> perc lci uci
#> K 1 5 9
#> L 2 6 10
#> M 3 7 11
#> N 4 8 12
# a single name is recycled, so this sets all the names to an empty string
setNamesX(diag(6), rownames="", colnames="")
#>
#> 1 0 0 0 0 0
#> 0 1 0 0 0 0
#> 0 0 1 0 0 0
#> 0 0 0 1 0 0
#> 0 0 0 0 1 0
#> 0 0 0 0 0 1
# any other length must fit, a mismatch is an error
try(setNamesX(matrix(c(1:12), nrow=4), colnames=c("perc", "lci")))
#> Error : length of 'colnames' [2] not equal to extent [3]
# setting dimnames works as well
tab <- setNamesX(
as.table(rbind(c(84,43), c(10,92))),
dimnames= list(
dipstick=c("positive","negative"),
culture=c("positive","negative")))
