k13
k13

Reputation: 723

Reorganize data.frame into tabulation of values

df <- data.frame(x=c(1,2,1,2,3,3), y = c(letters[1:5],'a'), val = c(1:5, 9))
print(df)
  x y val
  1 a   1
  2 b   2
  1 c   3
  2 d   4
  3 e   5
  3 a   9

I want to create a function fun(df, rowname, colname, valname)that takes a dataframe, rowname, colname, and value inputs and returns a data.frame or matrix with row names, column names and values as shown below

fun(df, "x","y","val") should return

    1 2 3
 a  1 NA 9
 b  NA 2 NA
 c  3 NA NA
 d  NA 4  NA  
 e  NA NA 5

Upvotes: 1

Views: 31

Answers (1)

Bastien
Bastien

Reputation: 3097

The reshape2 library allows this kind of manipulation:

library(reshape2)

dcast(data=df, y~x, value.var = "val")

  y  1  2  3
1 a  1 NA  9
2 b NA  2 NA
3 c  3 NA NA
4 d NA  4 NA
5 e NA NA  5

Upvotes: 1

Related Questions