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

I want to use cast for data.table with a formula with the name of the columns as a 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 get the result:

 c1 1 2 3 1 ABC 2 A1 B1 C1 

I could do it with the command

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

But I want to run dcast in a function that has the column name parameter c1 as a string. for example

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

Therefore I would call

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

Hope anyone can help!

+7
r data.table reshape
source share
1 answer

dcast takes the formula as a string.

 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 ABC # 2: 2 A1 B1 C1 

Please note that you do not need to download reshape2 , and you can also only use dcast instead of dcast.data.table from versions 1.9.5 +

+7
source share

All Articles