这个问题没有很好地提出 - 所以我将展示如何使用每个学生参加的每个“科目”的数量来取出一个 kmeans 对象。实际上,您可能想要一个这样的 PCA,然后是 kmeans,但这为如何处理它提供了一个思路。
您首先需要将数据转换为合理的格式。我使用 dat 作为 CourseCodeSub 和 dat2 作为 StudentIDCourse:
library(dplyr)
library(tidyr)
dat <- dat %>%
mutate(subjects = strsplit(as.character(subjects), ",")) %>%
unnest(subjects)
dat2 <- dat2 %>%
mutate(course = strsplit(as.character(course), ",")) %>%
unnest(course) %>%
mutate(course = as.numeric(course))
现在您的数据是长格式的。接下来,我们将它们合并,得到每个学生的data.frame,以及每个学生的每个科目的数量:
totable <- left_join(dat2, dat, by = "course") %>%
group_by(student, subjects) %>%
summarise(number = n()) %>%
spread(subjects, number, fill = 0)
Source: local data frame [6 x 6]
student B C I J M
(fctr) (dbl) (dbl) (dbl) (dbl) (dbl)
1 S1 0 3 2 0 2
2 S2 2 0 0 1 2
3 S3 2 1 1 1 3
4 S4 1 2 3 1 1
5 S5 1 1 1 1 1
6 S7 1 0 0 0 1
现在我们可以做一个kmeans:
clustered <- kmeans(totable[,2:6], 3)
plot(totable[,2:6], col = clustered$cluster)
并查看哪个学生在哪个集群中:
cbind(totable$student, clustered$cluster)
[,1] [,2]
[1,] 1 2
[2,] 2 1
[3,] 3 1
[4,] 4 2
[5,] 5 3
[6,] 6 3