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

▼魔方 西西 提交于 2019-11-28 13:35:42
Max

Using ifelse function and %in% operator.

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

matching_a
# [1] 1 1 0 0 0 1 1
> 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
42-

I see that John Colby has already taken the path I was going to suggest, but thought I would make it more explicit.

The dyadic function %in% returns a logical vector and multiplying by 1 coerced to "numeric" mode. This could also be done with:

matching_a <- as.numeric(dataset %in% x) # Or

matching_a <- 0 + (dataset %in% x)

You should also look at ?match on which the %in% function is based.

I used a slight variation of John's approach above (and Max's solution) to generate a list of 'binary vectors' (for multiple matches) as follows:

library("plyr")

dataset<-c("a","b","c","d","x","y","z")
var1<-c("a","b","y","z")
var2<-c("c","d","x")
vars <- list(var1, var2)

binaryLst <- lapply(vars ,function(x){ifelse(dataset %in% x, 1, 0)})

output:

> binaryLst
[[1]]
[1] 1 1 0 0 0 1 1

[[2]]
[1] 0 0 1 1 1 0 0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!