r语言 - 更改转换中的默认分隔符



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

我正在将文件从长转换为宽,并得到以下标题:

value_1, value_2, value_3,...  

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

value1, value2, value3,... 

但是,对于超过 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)

该示例给出了列标题:

conc_1, conc_2, resp_1, resp_2

我希望列标题为:

conc1, conc2, resp1, resp2

我试过:

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

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

你不能

,因为该选项未合并到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

data.table 包(dev 版本 1.9.5)中的 dcast 现在具有"sep"参数。

根据 dbetebenner 提供的信息以及使用data.table改进dcast功能的另一个示例,您的示例变为:

> 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() 通过引用将列表和data.frames转换为data.tables

使用 data.table v1.9.6 进行测试。

一个选项:

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

最新更新