【问题标题】:Change default separator in cast更改强制转换中的默认分隔符
【发布时间】:2012-09-13 01:49:00
【问题描述】:

当 cast (dcast) 分配新的列标题时,是否可以更改默认分隔符?

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

value_1, value_2, value_3,...  

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

value1, value2, value3,... 

但是,对于超过 200,000 行的数据框,reshape 需要几分钟,而 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,因为给出一个符号也不会改变输出。

【问题讨论】:

  • 请附上一个可重现的例子。
  • @mplourde 我添加了一个例子。

标签: r reshape reshape2


【解决方案1】:

您不能,因为该选项未包含在 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

【讨论】:

  • 我知道替换名称很容易,但如果可能的话,我一直在寻找解决方法。我还有其他带有下划线的列标题,因此需要多几行代码 - 尽管它仍然很容易。
  • 的方式。你可以重写dcastreshape2 的内部函数,但这将是更多的工作并且完全没有必要。包装在一个函数中会使它保持相同的代码行数(只有 1 行)
【解决方案2】:

data.table 包(开发版本 1.9.5)中的 dcast 现在具有“sep”参数。

【讨论】:

  • 1.9.5 早已过时,上面的@arekolek 提供了一个更完整的答案,包含了这一点
【解决方案3】:

基于information provided by dbetebennerusing data.table for improved dcast functionality 的另一个示例,您的示例变为:

> 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 测试。

【讨论】:

    【解决方案4】:

    一个选项:

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

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多