R语言笔记: one-hot 处理为单个的

本文介绍了如何使用R语言将四分类的聚类结果`result`从原始格式(Id1234,数值)转换为单列形式(Id类别),通过one-hot编码实现,最后保存为csv文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

load("data/kmeans_result.Rdata")读出变量result,result是聚类结果,四分类。
读出来的result的大概长这样:

Id 1 2 3 4
1 0 0 0 1
2 1 0 0 0

下面的代码把他改成了这样:

Id 类别
1 4
2 1

代码在此:

load("data/kmeans_result.Rdata")
head(result)
# one-hot数据处理为单个的
source_data = result
new_result  <- matrix( nrow = nrow(source_data), ncol = 1)
rownames(new_result) <- rownames(source_data)
for(i in c(1:nrow(source_data))){
 temp = source_data[i,]
 print(sprintf("%dth row: %d",i,(which(temp>0))))
 new_result[i,1] = which(temp>0)
 }

print(new_result)
colnames(new_result) = c("myCluster")
save(new_result,file="kmeans_result_single.csv.Rdata")
head(new_result)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值