在cast中更改默认分隔符

day*_*yne 5 r reshape reshape2

在强制转换(dcast)分配新列标题时是否可以更改默认分隔符?

我正在将文件从long转换为wide,我得到以下标题:

value_1, value_2, value_3,...  
Run Code Online (Sandbox Code Playgroud)

在重塑时,您可以分配"sep"参数(sep ="")和列标题输出,就像我希望它们一样:

value1, value2, value3,... 
Run Code Online (Sandbox Code Playgroud)

但是,对于我的数据框,重塑需要几分钟,超过200,000行,而dcast需要几秒钟.dcast还按照我想要的顺序输出列,而reshape则没有.有没有简单的方法来使用dcast更改输出,还是需要手动更改列标题?

例如:

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)
Run Code Online (Sandbox Code Playgroud)

该示例给出了列标题:

conc_1, conc_2, resp_1, resp_2
Run Code Online (Sandbox Code Playgroud)

我想要列标题:

conc1, conc2, resp1, resp2
Run Code Online (Sandbox Code Playgroud)

我试过了:

dcast(example,id~variable+index,sep="")
Run Code Online (Sandbox Code Playgroud)

dcast似乎完全忽略了sep,因为给出一个符号也不会改变输出.

Mai*_*ura 3

你不能,因为该选项没有合并到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
Run Code Online (Sandbox Code Playgroud)