I am aiming to take certain columns to rows, where the columns share an id, for example students in a class group.
please see here:
Group Student1 Age1 Grade1 Student2 Age2 Grade2
1 1 Sarah 17 A John 16 B
2 2 Tom 15 B Harry 16 C
3 3 Mary 15 C Jack 18 A
I would like this data so that each row is a student not the group as above:
Group Student Age Grade
1 1 Sarah 17 A
2 1 John 16 B
3 2 Tom 15 B
4 2 Harry 16 C
5 3 Mary 15 C
6 3 Jack 18 A
I have tried using
newData <- melt(dat, id.vars = c("id"))
but this gives me a list of id and all the other values as a column. Is there a function to get the result above?
Data:
dat <- structure(
list(
Group = 1:3,
Student1 = c("Sarah", "Tom", "Mary"),
Age1 = c(17L, 15L, 15L),
Grade1 = c("A", "B", "C"),
Student2 = c("John", "Harry", "Jack"),
Age2 = c(16L, 16L, 18L),
Grade2 = c("B", "C", "A")
),
class = "data.frame",
row.names = c(NA,-3L)
)