waterling waterling - 22 days ago 6
R Question

Levels in R from vector

lvl
is a list containing character vectors.

> lvl["Region"]
$Region
[1] "USA" "LONDON" "SINGAPORE"

> factor("USA", levels=lvl["Region"])
[1] <NA>
Levels: c("USA", "LONDON", "SINGAPORE")

> factor("USA", levels=c("USA", "LONDON", "SINGAPORE"))
[1] USA
Levels: USA LONDON SINGAPORE


The third statement is as expected. Why does the second statement create only 1 level?

Answer

It seems like 'lvl' is a list.

The lvl['Region'] is still a list with a single element

is.list(lvl['Region'])
#[1] TRUE

and levels argument in factor take vector. In order to extract the vector, use [[

factor("USA", levels=lvl[["Region"]])
#[1] USA
#Levels: USA LONDON SINGAPORE

data

lvl <- list(Region = c("USA", "LONDON", "SINGAPORE"))