将分类属性向量转换为相似度矩阵

编程入门 行业动态 更新时间:2024-10-26 08:26:17
本文介绍了将分类属性向量转换为相似度矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用R将分类属性向量转换为相同属性矩阵".

I need to transfrom a categorical attribute vector into a "same attribute matrix" using R.

例如,我有一个向量,该向量报告N人的性别(男性= 1,女性= 0).我需要将此向量转换为名为A的NxN矩阵(行和列上都有人的名字),如果两个人(i和j)的性别相同,则每个单元格Aij的值为1,否则为0.

For example I have a vector which reports gender of N people (male = 1, female = 0). I need to convert this vector into a NxN matrix named A (with people names on rows and columns), where each cell Aij has the value of 1 if two persons (i and j) have the same gender and 0 otherwise.

下面是一个示例,其中有3个人(第一位男性,第二位女性,第三位男性)产生此向量:

Here is an example with 3 persons, first male, second female, third male, which produce this vector:

c(1, 0, 1)

我想将其转换为这个矩阵:

I want to transform it into this matrix:

A = matrix( c(1, 0, 1, 0, 1, 0, 1, 0, 1), nrow=3, ncol=3, byrow = TRUE)

推荐答案

像lmo所说,不可能知道数据集的结构,因此下面仅是一个示例,供您了解如何完成. 首先,整理一些数据.

Like lmo said in acomment it's impossible to know the structure of your dataset so what follows is just an example for you to see how it could be done. First, make up some data.

set.seed(3488) # make the results reproducible x <- LETTERS[1:5] y <- sample(0:1, 5, TRUE) df <- data.frame(x, y)

现在根据需要将其制成表格

Now tabulate it according to your needs

A <- outer(df$y, df$y, function(a, b) as.integer(a == b)) dimnames(A) <- list(df$x, df$x) A # A B C D E #A 1 1 1 0 0 #B 1 1 1 0 0 #C 1 1 1 0 0 #D 0 0 0 1 1 #E 0 0 0 1 1

更多推荐

将分类属性向量转换为相似度矩阵

本文发布于:2023-10-27 03:43:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532207.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   矩阵   转换为   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!