C8H10N4O2
C8H10N4O2

Reputation: 19005

prevent renaming of vector elements assigned from another vector

I have a character vector (in this case, hex colors).

somePalette <- structure( c( "#F6B436", "#4D86A0","#672767"), 
                          .Names = c("Yellow", "Blue", "Purple")
  )
pie(c(1,1,1),col=somePalette)

From this vector, I wish to choose a few elements to pass to another vector (in this case, for use as the values= argument to ggplot2::scale_color_manual).

cols <- c("setosa" = somePalette["Yellow"],
          "versicolor" = somePalette["Blue"],
          "virginica" =  somePalette["Purple"])

# This doesn't work
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, col = Species)) +
  geom_point(size=5) +
  scale_color_manual(values=cols)

It seems that the element names I tried to assign have been changed, depending on the index of the element I passed:

> print(cols)
   setosa.Yellow  versicolor.Blue virginica.Purple 
       "#F6B436"        "#4D86A0"        "#672767" 

The following workaround produces the desired output:

# This works, though
cols2 <- c("setosa" = "#F6B436",
           "versicolor" = "#4D86A0",
           "virginica" =  "#672767")
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, col = Species)) +
  geom_point(size=5) +
  scale_color_manual(values=cols2)

Why does this renaming happen? (If it's not a bug, a link to documentation on this behavior would be much appreciated.) What's the easiest way to stop it from happening?

Upvotes: 0

Views: 31

Answers (1)

bgoldst
bgoldst

Reputation: 35324

  • This happens because the people who wrote the c() function designed it that way. Personally, I don't see any strong rationale for it; I'd prefer if the names of operand vectors be stripped when an explicit name is specified in the enclosing c() call.

  • I can't find any documentation on this behavior.

  • I can think of the following approaches to stop it from happening:


1: unname().

c(setosa=unname(somePalette['Yellow']),versicolor=unname(somePalette['Blue']),virginica=unname(somePalette['Purple']));
##     setosa versicolor  virginica
##  "#F6B436"  "#4D86A0"  "#672767"

2: [[ indexing.

c(setosa=somePalette[['Yellow']],versicolor=somePalette[['Blue']],virginica=somePalette[['Purple']]);
##     setosa versicolor  virginica
##  "#F6B436"  "#4D86A0"  "#672767"

The usual form of indexing is [. [[ can be used to select a single element dropping names, whereas [ keeps them, e.g., in c(abc = 123)[1].

3: setNames() afterward.

setNames(c(somePalette['Yellow'],somePalette['Blue'],somePalette['Purple']),c('setosa','versicolor','virginica'));
##     setosa versicolor  virginica
##  "#F6B436"  "#4D86A0"  "#672767"

Upvotes: 2

Related Questions