14

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
Jeromy Anglim
  • 42,044
  • 23
  • 146
  • 250
Rob
  • 391
  • 1
  • 3
  • 8

2 Answers2

23

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.

Felix S
  • 4,432
  • 4
  • 26
  • 34
1

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

Rob
  • 391
  • 1
  • 3
  • 8
momobo
  • 166
  • 5