Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

r - How to create a binary vector with 1 if elements are part of the same vector?

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.

Here's an example:

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

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
> output1 = 1 * dataset %in% var1
> output2 = 1 * dataset %in% var2
> output1
[1] 1 1 0 0 0 1 1
> output2
[1] 0 0 1 1 1 0 0

Also, if you have many more matches to make than var1 and var2, it'll be useful to extend this to something like:

> vars = list(var1, var2)
> 1 * sapply(vars, function(x) dataset %in% x)
     [,1] [,2]
[1,]    1    0
[2,]    1    0
[3,]    0    1
[4,]    0    1
[5,]    0    1
[6,]    1    0
[7,]    1    0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...