Flo
Flo

Reputation: 7

Extracting a Group from a Cluster

I am working on a Clusteranalyses with R. I use the Allbus Dataset, from which I extracted 7 rows. With the followig Code I made my Cluster

library("haven")
AllbusDatensatz <- read_sav("AllbusAntworten.sav")

CDU <- AllbusDatensatz$pa22
CSU <- AllbusDatensatz$pa23
SPD <- AllbusDatensatz$pa24
FDP <- AllbusDatensatz$pa25
Linke <- AllbusDatensatz$pa26
Gruenen <- AllbusDatensatz$pa27
AfD <- AllbusDatensatz$pa28

UmbenannterDatensatz <- cbind(CDU, CSU, SPD, FDP, Linke, Gruenen, AfD)
BereinigterDatensatz <- na.omit(UmbenannterDatensatz)

AllbusCentroid <- clara(BereinigterDatensatz,4,metric = "manhattan")

From these four CLusters I would now like to extract all the members of the first Cluster. I then would like to compare this list with the initial Dataset AllbusDatensatz so I could get the avarage age of all members, which is also part of the Dataset.

If someone could help me with my problem I would be very thankful.

Upvotes: 0

Views: 55

Answers (1)

s__
s__

Reputation: 9485

Due you've not given any data, here an example with some fake data:

library(cluster)
clarax <- clara(x,4,metric = "manhattan")

As written here, you've to fetch the vector of clusters:

clarax$clustering

And put it in your original data, then subset the desired rows:

# add vector of clustering
x$clust <- clarax$clustering
# subset the part of cluster == 1
x_cl1 <- x[x$clust == 1,]

Now you can calculate what you need.

mean(x_cl1[,1])

Note, the first cluster here is defined as the cluster marked with 1.


With data:

x <- structure(list(X1 = c(-4.58075844925284, 0.0652767299325834, 
-3.77639403053622, 2.74184342257295, -1.55283663415684, -0.646564270393359, 
1.98008127381616, 8.97937011921846, 17.0830608896667, -0.373624506395029, 
2.60144234508749, 1.32892095552686, 1.54997041572331, -5.94773087812292, 
8.30056236715301, 18.1001844129369, 24.1689939024213, 1.10899749796051, 
1.53087100550846, -6.04743527148338), X2 = c(52.8099714292224, 
38.3531449094573, 46.3760873669732, 51.7026666617339, 48.5273685430924, 
55.6277967599455, 51.2257527215893, 45.8741668783965, 46.805479767603, 
38.5446380799866, 33.9186743463602, 52.7066337605415, 55.2102957192513, 
69.4652121754147, 59.5307056986744, 57.3795425387994, 54.9687789881024, 
52.8506678644467, 50.5691711634846, 55.8544208074441), clust = c(1L, 
2L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 2L, 1L, 1L, 4L, 3L, 3L, 3L, 
1L, 1L, 1L)), row.names = c(NA, -20L), class = "data.frame")

Upvotes: 1

Related Questions