Changing the default delimiter in an application

Is it possible to change the default delimiter when cast (dcast) assigns new column headers?

I convert the file from long to wide, and get the following headers:

value_1, value_2, value_3,...  

In change mode, you can assign the sep parameter (sep = "") and display the column headers as I want them:

value1, value2, value3,... 

However, my data frame requires more than 200,000 rows, while dcast takes seconds. dcast also displays the columns in the order I want, where reshape is not. Is there an easy way to change the output using dcast or do I need to manually change the column headers?

For instance:

example <- data.frame(id=rep(c(1,2,3,4),4),index=c(rep(1,4),rep(2,4),rep(1,4),rep(2,4)),variable=c(rep("resp",8),rep("conc",8)),value=rnorm(16,5,1))
dcast(example,id~variable+index)

The example shows the column headings:

conc_1, conc_2, resp_1, resp_2

I want the column headers to be read:

conc1, conc2, resp1, resp2

I tried:

dcast(example,id~variable+index,sep="")

dcast seems to completely ignore sep, as providing a character also does not change the result.

+5
4

, dcast. , dcast.

casted_data <- dcast(example,id~variable+index)


library(stringr)
names(casted_data) <- str_replace(names(casted_data), "_", ".")

> casted_data
  id   conc.1   conc.2   resp.1   resp.2
1  1 5.554279 5.225686 5.684371 5.093170
2  2 4.826810 5.484334 5.270886 4.064688
3  3 5.650187 3.587773 3.881672 3.983080
4  4 4.327841 4.851891 5.628488 4.305907

# If you need to do this often, just wrap dcast in a function and 
# change the names before returning the result.

f <- function(df, ..., sep = ".") {
    res <- dcast(df, ...)
    names(res) <- str_replace(names(res), "_", sep)
    res
}

> f(example, id~variable+index, sep = "")
  id   conc1   conc2   resp1   resp2
1  1 5.554279 5.225686 5.684371 5.093170
2  2 4.826810 5.484334 5.270886 4.064688
3  3 5.650187 3.587773 3.881672 3.983080
4  4 4.327841 4.851891 5.628488 4.305907
+3

dcast data.table(dev 1.9.5) "sep".

+2

Based on the information provided by dbetebenner and another example , using data.tablefor enhanced functionalitydcast , your example will look like this:

> library(data.table)
> dcast(setDT(example), id ~ variable + index, sep="")
   id    conc1    conc2    resp1    resp2
1:  1 5.113707 5.475527 5.938592 4.149636
2:  2 4.261278 6.138082 5.277773 5.907054
3:  3 4.350663 4.292398 6.277582 4.167552
4:  4 5.993198 6.601669 5.232375 5.037936

setDT()It converts the lists and data.framesin data.tablesthe link.

Tested with data.tablev1.9.6.

+2
source

One option:

example <- data.frame(example,by=paste(example$variable,example$index,sep=""))
dcast(example,id~by)
+1
source

All Articles