Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dcast.data.table with formula as string

I want to use cast for a data.table with formula with name of columns as string

My table:

c1    c2    c3
1     A     1
1     B     2
1     C     3
2     A1    1
2     B1    2
2     C1    3

I want to have result:

c1    1    2    3
1     A    B    C
2     A1   B1   C1

I could do it with command

dcast.data.table(dt, c1 ~ c3, value.var = "c2")

But I want to run dcast in a function which has param of c1 column name as string. For example

f1 <- function(d, col_name1, col_name2, col_name3) {
  dcast.data.table(d, col_name1 ~ col_name3, value.var = col_name2)
}

So I would call

f1(dt, "c1", "c2", "c3")

Hope anyone can help!

like image 966
Minh Ha Pham Avatar asked Mar 27 '15 09:03

Minh Ha Pham


1 Answers

dcast accepts formula as a string as well.

f1 <- function(d, col_name1, col_name2, col_name3) {
    dcast.data.table(d, paste(col_name1, "~", col_name3), value.var = col_name2)
}

f1(dt, "c1", "c2", "c3")
#    c1  1  2  3
# 1:  1  A  B  C
# 2:  2 A1 B1 C1

Note that you don't have to load reshape2 and you can also directly use just dcast instead of dcast.data.table from versions 1.9.5+

like image 77
Arun Avatar answered Oct 22 '22 03:10

Arun