Why do the attributes for 'names' behave differently?

I am new to R and I do some google but I cannot find the answer.

var <- 1:2
attr(var,"name")<-'gg'
attr(var,"names")<-'gg'

However, when I check the attributes of var

attributes(var)
$name
[1] "gg"

$names
[1] "gg" NA  

Why for attributes names there is an NA? For var[1]?

I am using R studio, Version 0.99.491 on ubuntu

Upvotes: 3

Views: 125

Answers (1)

thelatemail
thelatemail

Reputation: 93928

When considering a basic, atomic vector like 1:2, names are attached to each individual element. Which means, if you don't give names to a particular element, R fills them in with NA values. I.e.:

var <- 1:2
names(var) <- c("a","b")
var
#   a b 
#   1 2 

var <- 1:2
names(var) <- c("a")
var
#   a <NA> 
#   1    2 

var <- 1:6
names(var) <- c("a","b")
var
#   a    b <NA> <NA> <NA> <NA> 
#   1    2    3    4    5    6

Upvotes: 4

Related Questions