如果元素是同一向量的一部分,如何创建具有 1 的二进制向量? [英] How to create a binary vector with 1 if elements are part of the same vector?

查看:17
本文介绍了如果元素是同一向量的一部分,如何创建具有 1 的二进制向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由二进制文件组成的所谓匹配向量.除非元素属于同一个变量,否则所有数字都应为零.

I would like to create a so-called matching vector consisting of binaries. All numbers should be zero unless elements belong to the same variable.

这是一个例子:

dataset=("a","b","c","d","x","y","z")
var1=c("a","b","y","z")
var2=c("c","d","x")

因此,我有一个数据集,其中包含第一行中的所有变量.现在我创建了两个组:var1 和 var2.

Thus, I have a dataset with all the variables in the first line. Now I create two groups: var1 and var2.

元素a"的匹配向量应该是这样的:

The matching vector for the element "a" is supposed to look like:

matching_a=c(1,1,0,0,0,1,1)

数字对应于我的数据集.如果我的数据集中的变量在同一组中,我的匹配向量中应该有 1,否则为 0.

The numbers correspond to my dataset. If the variables in my dataset are in the same group, there should be a 1 in my matching vector, and a 0 otherwise.

但是,我的实际数据集太大而无法手动完成.有人明白我想做什么吗?

However, my actual data set is too big to do it manually. Does anyone understand what I wanna do?

推荐答案

使用 ifelse 函数和 %in% 运算符.

Using ifelse function and %in% operator.

matching_a <-  ifelse(dataset %in% var1, 1, 0)

matching_a
# [1] 1 1 0 0 0 1 1

这篇关于如果元素是同一向量的一部分,如何创建具有 1 的二进制向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆