Reputation: 25
I have trouble reshaping my dataset correctly: I have some IVs and then 60 columns containing repeated measures (10 times) data of 6 blocks. Hence, I want to reshape the data to create one dependent variable and an additional new timevariable (1-10) and a new variable containing the information of the block (1-6).
I already tried reshaping twice, but I failed. The data looks like:
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
and should look like:
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
My code so far:
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")
And some example data (only two "blocks" of 5 repetitions):
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)
)
Thank you!
Upvotes: 2
Views: 193
Reputation: 1091
I'm not 100% sure I understand your question, but I think this is what you're looking for. Let me know if this isn't right. I haven't recoded the factor levels in the "Timepoint" column; I'll leave that as an exercise to you
library(tidyr)
library(magrittr)
mydata <- gather(example, key = "temp", value = "DV", -Sub, -IV1,
-IV2) %>%
separate(temp, c("Timepont", "Offersize"))
Gives output of
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
Upvotes: 1