I have a wide dataset composed of respondents' level variables (respondent
age
), along with the three dimensions of various objects presented to them (option_1
, category_1
, model_1
, option_2
, category_2
, model_2
,etc.). The initial dataset looks like this:
data <- as.data.frame(matrix(data = c("A", "21", "Option A", "Category C", "Model E",
"Option B", "Category C", "Model E",
"Option B", "Category D", "Model E",
"B", "35", "Option B", "Category D", "Model F",
"Option A", "Category D", "Model E",
"Option A", "Category D", "Model F"),
nrow = 2, ncol = 11, byrow = TRUE))
colnames(data) <- c("respondent", "age", "option_1", "category_1", "model_1",
"option_2", "category_2", "model_2",
"option_3", "category_3", "model_3")
data
I'm trying to transform it into a long-format, where each object presented to respondent is a row repeating the characteristics of the respondents and centralizing all three dimensions of the object. The target dataset would look like this:
data_target <- as.data.frame(matrix(data = c("A", "21", "Option A", "Category C", "Model E",
"A", "21", "Option B", "Category C", "Model E",
"A", "21", "Option B", "Category D", "Model E",
"B", "35", "Option B", "Category D", "Model F",
"B", "35", "Option A", "Category D", "Model E",
"B", "35", "Option A", "Category D", "Model F"),
nrow = 6, ncol = 5, byrow = TRUE))
colnames(data_target) <- c("respondent", "age", "option", "category", "model")
data_target
I'm struggling to automate the procedure, given that I need to bring some columns three by three as new rows while replicating the initial columns. Any idea how to do this?