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!