user1160927
user1160927

Reputation: 21

How to cluster a column with R

I have a dataframe

numbers = 1:4
letters = factor(c("a", "b", "c", "d"))
df <- data.frame(numbers, letters)
numbers letters
1       1       a
2       2       b
3       3       c
4       4       d

And I want to create a new column clustering the last column:

numbers letters
1       1       a      c1
2       2       b      c2
3       3       c      c1
4       4       d      c1

Is there a way to do that with R?

Upvotes: 2

Views: 5525

Answers (1)

John Colby
John Colby

Reputation: 22588

R has many different methods for clustering your data. Here is how you would do it with k-means, which is the most popular:

# Simulate data
data = data.frame(var1=rnorm(100), var2=rnorm(100), var3=c('a', 'b')[sample(2, 100, replace=T)])

# Convert factor variables to numeric 'dummy' variables
data.num = model.matrix(~ . - 1, data)

# Assign clusters
data$cl = kmeans(data.num, 2)$cluster

# Plot
dev.new(width=4, height=4)
with(data, plot(var1, var2, type='n'))
with(data, text(var1, var2, var3, col=cl))

enter image description here

Here the 2 clusters are identified by color, and are meaningless because the data are normally distributed, but you get the idea...

Upvotes: 2

Related Questions