Derrick Zhang
Derrick Zhang

Reputation: 21511

Is there an easy way to restore a factor object from its summary?

For example:

x <- c('A', 'A', 'B', 'C', 'C', 'C')
x <- as.factor(x)
print(summary(x))

will give the result:

A B C 
2 1 3 

Now if I have a named vector:

nv <- c(A=2, B=1, C=3)

How can I easily retain the x in the above example without caring about their order?

Thanks in advance.

Upvotes: 2

Views: 72

Answers (1)

Andrie
Andrie

Reputation: 179488

With your specific example, you can use rep, but take care: this is not a general solution. In fact, I believe a general solution is impossible, because summary discards information about the original vector.

x <- factor(c('A', 'A', 'B', 'C', 'C', 'C'))
xs <- summary(x)

rep(names(xs), times=xs)
[1] "A" "A" "B" "C" "C" "C"

The reason that this is not general is that summary really just give a contingency table, thus losing information about the position of the elements. For example, if I take your vector and append a few more A characters to the end, look what happens:

x <- factor(c('A', 'A', 'B', 'C', 'C', 'C', 'A', 'A'))
xs <- summary(x)

rep(names(xs), times=xs)
[1] "A" "A" "A" "A" "B" "C" "C" "C"

(You now have a sorted vector with all of the correct elements, but not in the correct order.)

Upvotes: 5

Related Questions