0

I read a lot on the internet and haven't found a solution. I have this data.frame:

d <- data.frame(cat = letters[11:15], count = c(1:10))
e <- data.frame(cat = letters[11:15], count = c(11:20))
G <- rbind(d, e)

   cat count
1    k     1
2    l     2
3    m     3
4    n     4
5    o     5
6    k     6
7    l     7
8    m     8
9    n     9
10   o    10
11   k    11
12   l    12
13   m    13
14   n    14
15   o    15
16   k    16
17   l    17
18   m    18
19   n    19
20   o    20

Now I want to transform the data frame to wide, but the count values need to be in rows like this:

cat  k  l  m  n  o
     1  2  3  4  5
     6  7  8  9 10
    11 12 13 14 15
    16 17 18 19 20

I have no idea, how to do it. Thank you in advance.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Erik Steiner
  • 581
  • 1
  • 5
  • 18
  • Do you have another column in your dataset to determine which values go to which row in your end result? Otherwise I'm not sure what's the logic for determining the order of values within each column. E.g. in column `k`, c(16, 11, 6, 1) would be as valid as c(1, 6, 11, 16)... – Z.Lin Aug 17 '17 at 09:38
  • cat k, l, m, n and o stands for account numbers of a daybook, while the count is the actual figure of the accounting transaction. So the journal collects all transactions row-wise and I now want to collect all transactions of account number k and throw them into a new column called k. The same for all other account numbers. To your last question, the order could be described by the order of the original data.frame so c(1,6,11,16) would be ok. – Erik Steiner Aug 17 '17 at 09:44

1 Answers1

1

We can use unstack

unstack(G, count~cat)
akrun
  • 874,273
  • 37
  • 540
  • 662