1

I have seen some examples that do this with only two variables, but I cannot quite figure out how to get it to work with my three variables (or if it can). I have 3 variables with 2-3 data points each -- it amounts to a 3x3x2 within-subjects ANOVA.

Here are a few lines of my data in wide form.
Variable headings indicate level of context, entropy, and distractor.

I have been looking at many examples of reshape, as well as melt and colsplit, but cannot figure out the solution that would work for my data. I know that if I just had the variable of Context with three levels (or three time points), I could get it to work, but with three different variables all with different levels is it possible?

Nissa
  • 4,636
  • 8
  • 29
  • 37
N.Dab
  • 11
  • 2
  • 1
    Do not post your data as an image, please learn how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Oct 19 '16 at 19:11
  • `library(data.table); ?melt.data.table` or `library(tidyr); ?gather`. – Brandon Bertelsen Oct 19 '16 at 20:18

1 Answers1

0

This might not be the most efficient way, but it works.

library(reshape2)
library(dplyr)
# create example dataset
my_df = data.frame(Subj_No = 314:318,
                   Context1_Entropy1_Dist1 = rep(1, 5),  
                   Context1_Entropy2_Dist1 = rep(2, 5),  
                   Context1_Entropy1_Dist2 = rep(3, 5),
                   Context1_Entropy2_Dist2 = rep(4, 5),
                   Context2_Entropy1_Dist1 = rep(5, 5),
                   Context2_Entropy2_Dist1 = rep(6, 5),
                   Context2_Entropy1_Dist2 = rep(7, 5),
                   Context2_Entropy2_Dist2 = rep(8, 5),
                   Context3_Entropy3_Dist2 = rep(9, 5),
                   Context3_Entropy3_Dist1 = rep(10, 5)) 

# melt data from wide to long form
my_df = melt(my_df, id.vars = "Subj_No", variable.name = "Group", 
             value.name = "Value")

# convert Group column to character
my_df$Group = as.character(my_df$Group)

# split group into three separate groups
groups = strsplit(my_df$Group, "_") %>% 
  unlist() %>% 
  matrix(ncol = 3, byrow = TRUE) %>%
  data.frame(stringsAsFactors = TRUE)

This part is to split the Group column into the three variables, Context, Entropy, and Dist with the delimiter "_", unlist, store as matrix by row, and convert to data.frame.

# some further processing
names(groups) = c("Context", "Entropy", "Dist")
levels(groups$Context) = 1:3
levels(groups$Entropy) = 1:3
levels(groups$Dist) = 1:2

Releveling is optional, but I thought that it might be easier for you to reference the groups by a number instead of something like "Context1", or "Entropy2".

# Combine the new groups with original df and drop Groups col
my_df = cbind(my_df, groups) %>% mutate(Group = NULL)

The last mutate function drops the Group variable.

I hope this is what you want!

acylam
  • 18,231
  • 5
  • 36
  • 45