1

I have the below dataframe:

      num   type         f
1:      1     aa    0.8103
2:      1     ba    0.7500
3:      2     bb    0.8602
4:      3     bb    0.9017
5:      3     aa    0.6308
6:      3     cc    0.8491

I'd like to rearrange my data so that my columns will be "num", the rows will be "type" and the values will be "f" and if there is no "f", it will write "0", as below:

             1        2         3
aa      0.8103        0    0.6308
ba      0.7500        0         0
bb           0   0.8602    0.9017
cc           0        0    0.8491      

Anyone know how can I rearrange my dataframe?

Bella
  • 937
  • 1
  • 13
  • 25

3 Answers3

4
library(tidyr)
df %>% spread(num, f, fill=0)

 type      1      2      3
  1   aa 0.8103 0.0000 0.6308
  2   ba 0.7500 0.0000 0.0000
  3   bb 0.0000 0.8602 0.9017
  4   cc 0.0000 0.0000 0.8491
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
2

Since you seem to use data.table, try

library(data.table)
dcast(data = df, type ~ num, fill = 0)
#  type      1      2      3
#1   aa 0.8103 0.0000 0.6308
#2   ba 0.7500 0.0000 0.0000
#3   bb 0.0000 0.8602 0.9017
#4   cc 0.0000 0.0000 0.8491
markus
  • 25,843
  • 5
  • 39
  • 58
2

A base R option is xtabs

xtabs(f ~ type + num, df1)
#    num
#type      1      2      3
#  aa 0.8103 0.0000 0.6308
#  ba 0.7500 0.0000 0.0000
#  bb 0.0000 0.8602 0.9017
#  cc 0.0000 0.0000 0.8491
akrun
  • 874,273
  • 37
  • 540
  • 662