【问题标题】:R Reshape data twiceR 重塑数据两次
【发布时间】:2018-11-07 21:18:34
【问题描述】:

我无法正确重塑我的数据集:我有一些 IV,然后是 60 列,其中包含 6 个块的重复测量(10 次)数据。因此,我想重塑数据以创建 一个 因变量和一个额外的新时间变量 (1-10) 和一个包含块信息的新变量 (1-6)。

我已经尝试过两次整形,但都失败了。数据如下:

 sbj  someIV    OfferCero.1   OfferCero.2 OfferCero.3 .... OfferFive.1 OfferFive.10 
   1   10         6               1           4                 1           4
   2   12         5               7           1                 2           3
   3   20         7               2           8                 5           2
   4   22         8               2           4                 4           1

应该看起来像:

sbj  someIV    DV     Timepoint     Offersize
 1   10         6         1             0         
 1   10         1         2             0
 1   10         4         3             0
 1   10         5         4             0

到目前为止我的代码:

First Reshape:

dl <- reshape(df, varying=list(CeroCent= c(32:41), OneCent= c(42:51), TwoCent= c(52:61), ThreeCent= c(62:71),FourCent= c(72:81), FiveCent= c(82:91) ), 
        v.names=c("CeroCent", "OneCent", "TwoCent", "ThreeCent", "FourCent", "FiveCent"),           
        direction="long",  
        times=1:10,
        timevar="Timepoint")

Second One: 
dl2 <- reshape(dl, direction="long", 
               varying= c(33:38),
               v.names="Emotion",
               times = 1:6, timevar="Offer")

还有一些示例数据(只有两个“块”,重复 5 次):

example <- data.frame(
  Sub = c(1:5),
  IV1 = sample(1:5),
  IV2 = sample(1:5),
  CeroCent.1 = sample(1:5),
  CeroCent.2 = sample(1:5),
  CeroCent.3 = sample(1:5),
  CeroCent.4 = sample(1:5),
  CeroCent.5 = sample(1:5),
  FiveCent.1 = sample(1:5),
  FiveCent.2 = sample(1:5),
  FiveCent.3 = sample(1:5),
  FiveCent.4 = sample(1:5),
  FiveCent.5 = sample(1:5)
)

谢谢!

【问题讨论】:

  • 还包括一个可重现的示例,而不仅仅是我们无法运行的代码视图。 Reproducible example

标签: r reshape transpose


【解决方案1】:

我不是 100% 确定我理解你的问题,但我认为这就是你要找的。让我知道这是否不正确。我没有在“时间点”列中重新编码因子水平;我会把它作为练习留给你

library(tidyr)
library(magrittr)
mydata <- gather(example, key = "temp", value = "DV", -Sub, -IV1, 
                 -IV2) %>% 
  separate(temp, c("Timepont", "Offersize"))

输出

  Sub IV1 IV2 Timepont Offersize DV
   1   4   3 CeroCent         1  4
   2   3   1 CeroCent         1  1
   3   1   2 CeroCent         1  2
   4   5   4 CeroCent         1  5
   5   2   5 CeroCent         1  3
   1   4   3 CeroCent         2  3

【讨论】:

  • 太好了,这就是我要找的!非常感谢
  • 不用担心,感谢您抽出宝贵时间来改进您的问题
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2017-04-05
  • 1970-01-01
  • 2017-09-18
相关资源
最近更新 更多