Reputation: 109
I'm havin an issue with R.
I have the following dataframe:
FirstName LastName Exercice1 Exercice2
Eric A 15 12
Eric A 14 14
Eric A 12 15
Paul B 12 14
Paul B 14 14
Joe C 15 12
Joe C 15 17
Joe C 16 17
Joe C 18 19
And I want to change it into the following:
FirstName LastName Mark
Exercice1 Exercice2
Eric A 15 12
14 14
12 15
Exercice1 Exercice2
Paul B 12 14
14 14
Exercice1 Exercice2
Joe C 15 12
15 17
16 17
18 19
In short I would like to group for each students their marks for every test into a single variable that is a data frame.
Do you have any ideas if that is possible and how I should do?
Upvotes: 0
Views: 248
Reputation: 6931
If all you need is the Mark column to be a data.frame of the student, then you can use this:
dat <- read.table(text = "FirstName LastName Exercice1 Exercice2
Eric A 15 12
Eric A 14 14
Eric A 12 15
Paul B 12 14
Paul B 14 14
Joe C 15 12
Joe C 15 17
Joe C 16 17
Joe C 18 19", stringsAsFactors = FALSE, header = TRUE)
dat2 <- dat[!duplicated(dat[,1:2]),1:2]
dat2$Mark <- I(split(dat[,3:4], list(dat$FirstName, dat$LastName), drop = TRUE))
dat2
# FirstName LastName Mark
#1 Eric A c(15, 14....
#4 Paul B c(12, 14....
#6 Joe C c(15, 15....
Mark is a list of dataframes:
> dat2$Mark
$Eric.A
Exercice1 Exercice2
1 15 12
2 14 14
3 12 15
$Paul.B
Exercice1 Exercice2
4 12 14
5 14 14
$Joe.C
Exercice1 Exercice2
6 15 12
7 15 17
8 16 17
9 18 19
Now in order to print like you showed you'd need a custom print function, but you shouldn't need that anyway. Or just add empty rows to get your desired print output. This isn't pretty nor like your output, but it's a start:
dat3 <- dat
dat3[duplicated(dat[,1:2]),1:2] <- ""
print(dat3, row.names = FALSE)
# FirstName LastName Exercice1 Exercice2
# Eric A 15 12
# 14 14
# 12 15
# Paul B 12 14
# 14 14
# Joe C 15 12
# 15 17
# 16 17
# 18 19
Upvotes: 3