0

this is pre-data

Name type cnt
Jay   A    1
Jay   B    2
John  A    3
John  B    6

how to set the data like this

Name A B 
Jay  1 2
John 3 6

data.frame() is not wokring as I expect. any idea?

here is my data for real

       Name    type cnt
1      Anne       A  30
2   Barbara       A  15
3       Ben       A  21
4     Cindy       A 100
5       Edd       A 105
6      Eric       A  22
7     Jacky       A  17
8      John       A  97
9       Lex       A  22
10     Nick       A  18
11     Paul       A 100
12     DoIt       B  66
13    FixIt       B  66
14     Anne       C 185
15  Barbara       C  88
16      Ben       C   4
17     Eric       C   4
18    Jacky       C  92
19      Lex       C   7
20     Nick       C   3
DK2
  • 651
  • 1
  • 7
  • 34
  • I got 'Error: Invalid column specification' message. I think it's because there are some missing data that cannot make 'completed spread frame data' – DK2 Jul 26 '15 at 08:22

1 Answers1

4

Using tidyr'sspread

library(tidyr)
spread(df, type, cnt, fill = 0)

Using reshape2's dcast

library(reshape2) 
dcast(df, Name ~ type, fill = 0)

#      Name   A  B   C
#1     Anne  30  0 185
#2  Barbara  15  0  88
#3      Ben  21  0   4
#4    Cindy 100  0   0
#5     DoIt   0 66   0
#6      Edd 105  0   0
#7     Eric  22  0   4
#8    FixIt   0 66   0
#9    Jacky  17  0  92
#10    John  97  0   0
#11     Lex  22  0   7
#12    Nick  18  0   3
#13    Paul 100  0   0

Or using base R

 reshape(df, idvar='Name', timevar='type', direction='wide')

Or

 xtabs(cnt~Name+type, df)

Or

 with(df, tapply(cnt, list(Name, type), FUN=I))
akrun
  • 874,273
  • 37
  • 540
  • 662
Veerendra Gadekar
  • 4,452
  • 19
  • 24
  • reshape2's dcast is working similarlly. is there any way replacing NA to 0? and Why my real data is not working with spread? I added my data on post – DK2 Jul 26 '15 at 08:37
  • @DongHunKim check the edited answer. for me spread is working too, make sure that you specify correct column names – Veerendra Gadekar Jul 26 '15 at 08:40
  • spread is still not working, but dcast works so well. thanks alot :) – DK2 Jul 26 '15 at 08:42