2016-07-12 3 views
-4

私は長い形式のデータを持っています。私はReshape関数を使用してワイド形式に再構成する必要があります。reshape関数を使用したデータの整形

ロング形式:

Project Value 
    Self 500 
Myself 300 
    Yours 400 
    Self 200 
Myself 600 
    Yours 700 
    Self 800 
Myself 900 
    Yours 200 

ワイドフォーマット:

Project Value Project1 Value1 Project2 Value2 
    Self 500 Myself 300 Yours 400 
    Self 200 Myself 600 Yours 700 
    Self 800 Myself 900 Yours 200 
+0

を使用してオプションであるあなたがその可能な形式でデータを提供する場合、あなたはより迅速に助けを取得しますRに直接読み込むことができます。これを作成する最も簡単な方法は 'dput(df)'を使用することです.dfはあなたのdatフレーム。 – Edwin

+0

改造なしのオプション: 'do.call(cbind、split(df、df $ Project))' –

+0

何を試しましたか?何が悪かったのか? – agenis

答えて

1

Docendo Discimusが示唆したように、簡単として行うことができます。ここで

> a 
    Project Value 
1 Self 500 
2 Myself 300 
3 Yours 400 
4 Self 200 
5 Myself 600 
6 Yours 700 
7 Self 800 
8 Myself 900 
9 Yours 200 

b <- do.call(cbind, split(a, a$Project)) 

> b 
    Myself.Project Myself.Value Self.Project Self.Value Yours.Project Yours.Value 
2   Myself   300   Self  500   Yours   400 
5   Myself   600   Self  200   Yours   700 
8   Myself   900   Self  800   Yours   200 
1
df$id <- ave(integer(nrow(df)),df$Project,FUN=seq_along); 
df$time <- ave(character(nrow(df)),df$id,FUN=function(x) c('',seq_len(length(x)-1L))); 
reshape(df,dir='w',sep='')[-1L]; 
## Project Value Project1 Value1 Project2 Value2 
## 1 Self 500 Myself 300 Yours 400 
## 4 Self 200 Myself 600 Yours 700 
## 7 Self 800 Myself 900 Yours 200 

データ

df <- data.frame(Project=c('Self','Myself','Yours','Self','Myself','Yours','Self','Myself', 
'Yours'),Value=c(500L,300L,400L,200L,600L,700L,800L,900L,200L),stringsAsFactors=F); 
1

こんにちはdata.table

library(data.table) 
dcast(setDT(df1)[, c("id", "id1") := .(1:.N, .GRP), Project], 
        id~ id1, value.var= c("Project", "Value"))[, id := NULL][] 
# Project_1 Project_2 Project_3 Value_1 Value_2 Value_3 
#1:  Self Myself  Yours  500  300  400 
#2:  Self Myself  Yours  200  600  700 
#3:  Self Myself  Yours  800  900  200 
関連する問題