使用重塑功能形成数据

时间:2016-07-12 10:39:33

标签: r

我有长格式的数据我需要使用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

3 个答案:

答案 0 :(得分: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 :(得分: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);

答案 2 :(得分: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