【问题标题】:match and add the cluster number to the original data匹配并将簇号添加到原始数据中
【发布时间】:2015-04-07 07:46:24
【问题描述】:

我正在使用常规方法做一个层次聚类项目。

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 

我想要的是将组号放回原始数据中的新列。 我看过approximate string matching within single list - r 因为这里的df是一个文档矩阵所以我在df &lt;- 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 

【问题讨论】:

  • 这很不优雅,但你能不能不这样做:ifelse[df$eye == "1", "3", "0")?对每一列重复,但相应地更改替换编号。最好使用 sapply 和查找表,但我还没有解决。
  • @lawyeR 谢谢,我用不那么优雅的方式做到了。

标签: r matching hclust


【解决方案1】:

我没有直接放回数字,而是使用 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

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

【讨论】:

    猜你喜欢
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多