Attributes of a vector with characters

Hi there!

I have the following R code:

Haircolour <- c("Brown","Brown","Black")
Age <- c(18,19,20)
Group <- data.frame(Haircolour, Age)

attributes(Group$Haircolour)

When I run the code, attributes(Group$Haircolour) gives me NULL. Why is this NULL and not a factor?

Haircolour <- c("Brown","Brown","Black")
Age <- c(18,19,20)
Group <- data.frame(Haircolour, Age)

Group$Haircolour <- as.factor(Haircolour)
str(Group)
#> 'data.frame':    3 obs. of  2 variables:
#>  $ Haircolour: Factor w/ 2 levels "Black","Brown": 2 2 1
#>  $ Age       : num  18 19 20
attributes(Group$Haircolour)
#> $levels
#> [1] "Black" "Brown"
#> 
#> $class
#> [1] "factor"

Think of attributes as tags. A vector doesn't have them unless expressly set (you'll see this as an "atomic vector"). Functions, like as.factor(), can set them, but not all do.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.