Solution for fill cells in a matrix with one and zeros
is Given Below:
I have the next problem:
I have a column with some identificators, for instance:
id<-c("id1","id2","id3","id4","id5","id6","id7","id8","id9","id10")
then I have have three vectors
v1<- c("id3","id5","id7")
v2<- c("id1","id2","id10","id8")
v3<- c("id5","id9","id10","id3")
I need to create a table, where the first column is the id column (with all the id´s in the three vectors)
Then I need to add three columns in the table and in each column put a 1 if the respective id appears in the vector, and 0 otherwise.
The expected output is something like this
vv1<-c(0,0,1,0,1,0,1,0,0,0)
vv2<-c(1,1,0,0,0,0,0,1,0,1)
vv3<-c(0,0,1,0,1,0,1,0,1,1)
output<- data.frame(id,vv1,vv2,vv3)
I need this idea in order to replicate the same with a big vector of id’s, around 3M.
Suppose your vectors look like
id <-c("id1","id2","id3","id4","id5","id6","id7","id8","id9","id10")
v1 <- c("id3","id5","id7")
v2 <- c("id1","id2","id10","id8")
v3 <- c("id5","id9","id10","id3")
data.frame(id,
vv1 = as.integer(id %in% v1),
vv2 = as.integer(id %in% v2),
vv3 = as.integer(id %in% v3))
returns
id vv1 vv2 vv3
1 id1 0 1 0
2 id2 0 1 0
3 id3 1 0 1
4 id4 0 0 0
5 id5 1 0 1
6 id6 0 0 0
7 id7 1 0 0
8 id8 0 1 0
9 id9 0 0 1
10 id10 0 1 1