错误的基本重塑功能,从长到长的格式

时间:2017-09-19 04:29:33

标签: r

我有以下宽格式数据框:

df<-structure(list(ID = c(1, 2, 3), A.1 = c(0, 1, 0), A.2 = c(1, 
1, 0), B.1 = c(99, 99, 0), B.2 = c(99, 99, 0)), .Names = c("ID", 
"A.1", "A.2", "B.1", "B.2"), row.names = c(NA, 3L), class = "data.frame")

   > df

  ID A.1 A.2 B.1 B.2
1  1   0   1  99  99
2  2   1   1  99  99
3  3   0   0   0   0

现在我将其更改为长格式:

long.df<-reshape (df,idvar = "ID", varying=c(2:5),v.names= c("A", "B"), 
timevar="time",direction="long", sep = ".") 

以下是生成的长数据框:

 > long.df
     ID time  A  B
 1.1  1    1  0  1
 2.1  2    1  1  1
 3.1  3    1  0  0
 1.2  1    2 99 99
 2.2  2    2 99 99
 3.2  3    2  0  0

因此,此转换不正确,值变得混乱。例如,时间点1的ID 1的参数B的值从99变为1,参数A的值在第二时间点的ID 1和2变为99,依此类推。

预期输出应如下:

 > expected.long.df
     ID time A  B
 1.1  1    1 0 99
 2.1  2    1 1 99
 3.1  3    1 0  0
 1.2  1    2 1 99
 2.2  2    2 1 99
 3.2  3    2 0  0

不知道为什么会这样。对任何建议都会非常有帮助。

4 个答案:

答案 0 :(得分:4)

问题发生在varying。我们需要正确指定模式

reshape(df, idvar = "ID", varying = list(grep("^A", names(df)),
      grep("^B", names(df))), direction = "long", v.names = c("A", "B"))
#    ID time A  B
#1.1  1    1 0 99
#2.1  2    1 1 99
#3.1  3    1 0  0
#1.2  1    2 1 99
#2.2  2    2 1 99
#3.2  3    2 0  0

答案 1 :(得分:2)

我会使用tidyr库:

library(tidyr)
temp1 = gather(df, key = "x", value = "y", -ID)
temp2 = separate(temp1, x, into = c("z", "time"), sep = "[.]")
temp3 = spread(temp2, key = z, value = y)

temp3表看起来像您想要的结果,但不是完全相同的顺序。使用dplyr的{​​{1}}来做对:

arrange

答案 2 :(得分:2)

试试这个。您实际上是在查看melt操作。

library(data.table)
df<-structure(list(ID = c(1, 2, 3), A.1 = c(0, 1, 0), A.2 = c(1, 1, 0), B.1 = c(99, 99, 0), B.2 = c(99, 99, 0)), .Names = c("ID", "A.1", "A.2", "B.1", "B.2"), row.names = c(NA, 3L), class = "data.frame")
dt <- setDT(df)
melt(dt, id = 'ID', measure = patterns('^A.', '^B.'), value.name = c('A', 'B'), variable.name = 'time')
   ID time A  B
1:  1    1 0 99
2:  2    1 1 99
3:  3    1 0  0
4:  1    2 1 99
5:  2    2 1 99
6:  3    2 0  0

答案 3 :(得分:2)

以你reshapestringrstr_split_fixed

为基础
df=melt(df,'ID')
df[,c('Time','Name')]=str_split_fixed(as.character(df$variable),"[.]",2)
df$variable=NULL
reshape(df, idvar = c("ID","Name"), timevar = "Time", direction = "wide")

  ID Name value.A value.B
1  1    1       0      99
2  2    1       1      99
3  3    1       0       0
4  1    2       1      99
5  2    2       1      99
6  3    2       0       0