[R] Help with unlist

Marc Schwartz MSchwartz at mn.rr.com
Sun Oct 29 17:23:29 CET 2006


On Sun, 2006-10-29 at 10:43 -0500, Michael Kubovy wrote:
> Dear r-helpers,
> 
> I have a list whose elements are
> 
>  > str(durCut[[1]])
> Ord.factor w/ 5 levels "vLow"<"low"<"med"<..: 3 2 5 2 2 2 4 4 3 5 ...
> 
> How do I unlist durCut into an ordered factor?
> 
>  > str(unlist(durCut))
> int [1:3024] 3 2 5 2 2 2 4 4 3 5 ...

You might want to check:

  str(durCut)

to be sure that all of the list elements are ordered factors.

For example:

> Ord.List <- replicate(5, list(factor(letters[1:5], ordered = TRUE)))
> Ord.List
[[1]]
[1] a b c d e
Levels: a < b < c < d < e

[[2]]
[1] a b c d e
Levels: a < b < c < d < e

[[3]]
[1] a b c d e
Levels: a < b < c < d < e

[[4]]
[1] a b c d e
Levels: a < b < c < d < e

[[5]]
[1] a b c d e
Levels: a < b < c < d < e


> unlist(Ord.List)
 [1] a b c d e a b c d e a b c d e a b c d e a b c d e
Levels: a b c d e

retains the factor component, though the ordered attribute is lost, so:

> factor(unlist(Ord.List), ordered = TRUE)
 [1] a b c d e a b c d e a b c d e a b c d e a b c d e
Levels: a < b < c < d < e


However, if even one of the list elements is, say numeric:

> Ord.List2 <- list(factor(letters[1:5], ordered = TRUE), 1:5)
> Ord.List2
[[1]]
[1] a b c d e
Levels: a < b < c < d < e

[[2]]
[1] 1 2 3 4 5

> unlist(Ord.List2)
 [1] 1 2 3 4 5 1 2 3 4 5


So my guess is that at least one of the elements in 'durCut' is probably
numeric.

BTW, this is covered in the Details section of ?unlist:

"Factors are treated specially. If all non-list elements of x are
factors (or ordered factors) then the result will be a factor with
levels the union of the level sets of the elements, in the order the
levels occur in the level sets of the elements (which means that if all
the elements have the same level set, that is the level set of the
result)."

...

"Where possible the list elements are coerced to a common mode during
the unlisting, and so the result often ends up as a character vector.
Vectors will be corced to the highest type of the components in the
hierarchy NULL < raw < logical < integer < real < complex < character <
list < expression: pairlists are treated as lists."


HTH,

Marc Schwartz


P.S. To R Core, note the typo in the second quoted passage, where
'coerced' is spelled 'corced'.  R 2.4.0 patched, r39576.



More information about the R-help mailing list