14
votes
$\begingroup$

Using R or Excel, what is the easiest way to convert a frequency table into a vector of values?

E.g., How would you convert the following frequency table

Value   Frequency
  1.      2
  2.      1
  3.      4
  4.      2
  5.      1

into the following vector?

1, 1, 2, 3, 3, 3, 3, 4, 4, 5
$\endgroup$

2 Answers 2

23
votes
$\begingroup$

In R, you can do it using the repcommand:

tab <- data.frame(value=c(1, 2, 3, 4, 5), freq=c(2, 1, 4, 2, 1))
vec <- rep(tab$value, tab$freq)

This gives following result:

> tab
  value freq
1     1    2
2     2    1
3     3    4
4     4    2
5     5    1

> vec
 [1] 1 1 2 3 3 3 3 4 4 5

For details, see the help file for the repcommand by typing ?rep.

$\endgroup$
1
  • 2
    $\begingroup$ Or, given a simple frequency table for vec <- sample(1:5, 20, TRUE) created by table(): rep(names(table(vec)), table(vec)). The result then needs to be converted with as.numeric() if the categories are actual numbers. $\endgroup$
    – caracal
    Commented Sep 15, 2011 at 6:40
1
vote
$\begingroup$

Obviously in R it's simpler.

In Excel I would use a helper column (if the value is in A1):

  value freq help
1     1    2  =REPT(A2 & ", ",B2)
2     2    1  =C1 & REPT(A3 & ", ",B3)
3     3    4  (drag or copy from upper cell)
4     4    2  (drag or copy from upper cell)
5     5    1  (drag or copy from upper cell)
              =LEFT(C6, LEN(C6)-1)

In C7 you have your result

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.