5

キャスト (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 を完全に無視しているように見えます。

4

4 に答える 4

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
于 2012-09-20T17:17:19.413 に答える
3

data.table パッケージ (dev バージョン 1.9.5) の dcast には、'sep' 引数が追加されました。

于 2015-07-08T00:53:41.640 に答える
2

dbetebenner によって提供された情報と、機能改善のために使用data.tabledcastする別の例に基づいて、例は次のようになります。

> 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.tablev1.9.6でテスト済み。

于 2016-03-30T09:35:40.430 に答える
1

1つのオプション:

example <- data.frame(example,by=paste(example$variable,example$index,sep=""))
dcast(example,id~by)
于 2012-09-20T17:22:30.267 に答える