Question: Kmeans in R for clustering on significant gene list by sample
gravatar for myyid68
12 months ago by
myyid6830 wrote:


I'm completely new to bioinformatics and machine learning. I have a dataframe with pre-processed data where rows are genes and columns are samples (column 1 is probe ID, then the rest of columns are cancer samples and normal samples). I want to use kmeans in R to do clustering on my data by samples with 2 as the initial number of clusters. So far I have been doing some research on kmeans clustering and came up with the code below which seems to be working but since I'm new to this, not sure if this is correct? Also I want to draw a line chart to indicate the profile of the 2 clusters by using the center of each cluster but dont know how to do that.. Perhaps someone can help me with some guidance, examples of how to do this properly? Thank you!

clustering<- kmeans(df[ ,2:21], 2)
new <- cbind(df, cluster = clustering$cluster)
ADD COMMENTlink modified 12 months ago by KevinBlighe66k • written 12 months ago by myyid6830
gravatar for KevinBlighe
12 months ago by
KevinBlighe66k wrote:


Yes, this is the correct way to do k-means, and, indeed, the cluster assignments will be stored in the cluster variable.

Reproducible example:

randomdata <- matrix(rexp(200, rate=.1), ncol=20)
rownames(randomdata) <- paste0('gene', 1:nrow(randomdata))
colnames(randomdata) <- paste0('sample', 1:ncol(randomdata))
randomdata[1:5, 1:5]
        sample1   sample2   sample3   sample4   sample5
gene1 21.787478  2.392901  9.403012 24.550271 12.001397
gene2  5.789860  3.443809 23.343598  6.380007  4.524190
gene3 20.624568  3.497594 18.989897 11.694150  4.254307
gene4  5.117409  6.021590  2.004472  5.939098  1.801671
gene5 10.875161 12.953176 20.717515  3.199971  8.246331

k <- kmeans(randomdata, centers = 2)
 gene1  gene2  gene3  gene4  gene5  gene6  gene7  gene8  gene9 gene10 
     2      2      2      2      2      2      2      1      2      2

You can then access the centers like this, for example:

plot(k$centers[1,], type = 'l', lwd = 2, col = 'red2')
lines(k$centers[2,], type = 'l', lwd = 2, col = 'royalblue')


ADD COMMENTlink written 12 months ago by KevinBlighe66k

Thank you so much, Kevin, that's very helpful!

ADD REPLYlink written 12 months ago by myyid6830
Please log in to add an answer.


Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 685 users visited in the last hour