1

I have seen this post (How to access the last value in a vector?) showing how to use the tail function. When I apply tail to a factor, it returns all the levels of the factor, including the last factor to appear. Example:

x = rep(1:4, 6)
y =  rnorm(4*length(x), 0, 0.1)

d = data.frame(ERF=x, y)

d$ERF = factor(d$ERF)

a <- tail(d$ERF, n=1)

> a
[1] 4
Levels: 1 2 3 4

I just want to store the last factor as a variable (a). I can see that a[1] is 4 but:

> a[1]
[1] 4
Levels: 1 2 3 4

I looked at ?tail but cant seem to figure it out. I know it must be simple I just need a nudge in the right direction. Thanks

Community
  • 1
  • 1
Pete900
  • 2,016
  • 1
  • 21
  • 44

2 Answers2

4

tail, like any indexing function, returns elements. However, an element of a factor is still a factor, so when you print it all the factor levels are printed.

Nevertheless, you can use that value as any other value. If you want to use the value itself, transform it into a character string via as.character.

If you want to get rid of all unused factor levels, use droplevels:

f = factor(letters)

tail(f)
# [1] u v w x y z
# Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z

as.character(tail(f))
# [1] "u" "v" "w" "x" "y" "z"

droplevels(tail(f))
# [1] u v w x y z
# Levels: u v w x y z
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Just a small comment, the `factor` levels not only printed, but they are actually stored there too as `attributes(tail(f))` will reveal. – David Arenburg Jul 27 '15 at 10:11
2

You can just use factor(a)

> a
[1] 4
Levels: 1 2 3 4
> factor(a)
[1] 4
Levels: 4
RHertel
  • 23,412
  • 5
  • 38
  • 64