1

我正在使用常规方法进行层次聚类项目。

mydata.dtm <- TermDocumentMatrix(mydata.corpus)
mydata.dtm2 <- removeSparseTerms(mydata.dtm, sparse=0.98)
mydata.df <- as.data.frame(inspect(mydata.dtm2))
mydata.df.scale <- scale(mydata.df)
d <- dist(mydata.df.scale, method = "euclidean") # distance matrix
fit <- hclust(d, method="ward")
groups <- cutree(fit, k=10)

groups
              congestion        cough          ear          eye        fever          flu   fluzonenon     medicare painpressure     physical         pink          ppd     pressure 
                       1            2            3            4            5            6            5            5            5            7            4            8            5 
                    rash    screening         shot        sinus         sore       sports     symptoms       throat          uti 
                       5            5            6            1            9            7            5            9           10 

而我想要的是将组号放回原始数据中的新列。我已经查看了单个列表中的近似字符串匹配 - r 因为这里的 df 是一个文档矩阵,所以我得到df <- t(data.frame(mydata.df.scale,cutree(hc,k=10)))的是一个类似的矩阵

df[1:5,1:5]
     congestion cough ear eye fever
[1,]          0     0   0   0     0
[2,]          0     0   0   0     0
[3,]          0     0   0   0     0
[4,]          0     0   0   1     0
[5,]          0     0   0   0     0

由于 eye 的组号为 3,因此我想将数字 3 添加到第 4 行的新列中。

请注意,在这种情况下,单个文档可以映射到同一组中的两个项目。

df[23,17:21]
   sinus     sore   sports symptoms   throat 
       0        1        0        0        1 
4

1 回答 1

0

我没有直接放回数字,而是使用 0-1 矩阵:

label_back <-t(data.frame(mydata.df,cutree(fit,k=10))) 
row.names(label_back) <- NULL

#label_back<-label_back[1:(nrow(label_back)-1),]# the last line is the sum
groups.df<-as.data.frame(groups)
groups.df$label<-rownames(groups.df)

for (i in 1:length((colnames(label_back)))){
ind<-which(colnames(label_back)[i]==groups.df$label) # match names and return index
label_back[,i]=groups.df$groups[ind]*label_back[,i]  # time the 0-1 with the #group number
     }

在每一行中找到最大值,因为在某些行中有超过 1 个值。

data_group<-rep(0,nrow(data)

for (i in 1:nrow(data)){
  data_group[i]<-max(unique(label_back[i,]))
}
data$group<-data_group

我正在寻找更优雅的方式。

于 2015-02-07T17:07:18.293 回答