Names combined by dot automatically when assign value of a named array with a named variable

Viewed 55

A simple example:

a <- quantile(1:10, 0.1)
a

output:

10%
1.9

Use a to assign value of a named array:

b = c(index=0, value=a)
b

output:

index value.10%
 0.0     1.9

Why the 'value' and '10%' are combined by dot automatically? How to avoid this, as I just want to name it as 'value'?

2 Answers

The b object created in the question is an R named vector, not an R array.

array

An R array is an R vector with a dimension (or dimensions) and possibly a dimnames attribute. It is created like this:

ar <- array(c(0, a), dimnames = list(c("index", "value"))); ar
## index value 
##   0.0   1.9 

named vector

To create a named vector with specified names rather than creating an array use setNames to overwrite any existing names:

v <- setNames(c(0, a), c("index", "value")); v
## index value 
##   0.0   1.9 

or use names<- like this:

v <- c(0, a)
names(v) <- c("index", "value")

or as mentioned in the comments already, create b from unname(a) rather than from a to avoid the combined names.

attributes

Note that the attributes of ar are:

attributes(ar)
## List of 2
##  $ dim     : int 2
##  $ dimnames:List of 1
##   ..$ : chr [1:2] "index" "value"

and the attributes of v are:

attributes(v)
## $names
## [1] "index" "value"

Answers in comment help you for this problem but I think that you have to understand the fact that a is already a named vector. So using c (c for concat) here you try to concat two objects not of the same type. That's why R tries to make it work by concatenating names, here the the orignal one (10%) and the one you want to give.

In this context it would make more sense to me to write c(c(index=0), a) and then to change names, or c(index=0, value=unname(a))

Related