0 votes
1 view
in R Programming by (42.1k points)

I am having a matrix that contains the indices of column ids to the element of matrix:

>  index

         [,1] [,2] [,3] 

    [1,]    1    NA   3    

    [2,]    1    2    NA    

    [3,]    1    3    NA    

    [4,]    1    3    5    

    [5,]    1    4    5    

    [6,]    2    NA   NA    

    [7,]    3    4    NA  

In the above data frame the first row is having the column id 1 ,NA , 3 that set to it value 1 and ignore NA.

The second row also have the column id 1 , 2 , NA that set to it value 1

Now what I want is to create the following matrix:

     a1 a2 a3  a4 a5

[1,]  1  0  1  0  0

[2,]  1  1  0  0  0

[3,]  1  0  1  0  0

[4,]  1  0  1  0  1

[5,]  1  0  0  1  1  

[6,]  0  1  0  0  0

[7,]  0  0  1  1  0

1 Answer

0 votes
by (90.8k points)

You can easily create a matrix of 0's where number of rows is same as index and number of columns is the maximum value in index. We could then create a row, column matrix using row function as row index and index values as column index and turn them to 1.

mat <- matrix(0, ncol = max(index, na.rm = TRUE), nrow = nrow(index))

mat[cbind(c(row(index)), c(index))] <- 1

mat

#     [,1] [,2] [,3] [,4] [,5]

#[1,]    1    0    1    0    0

#[2,]    1    1    0    0    0

#[3,]    1    0    1    0    0

#[4,]    1    0    1    0    1

#[5,]    1    0    0    1    1

#[6,]    0    1    0    0    0

#[7,]    0    0    1    1    0

data

index <- structure(c(1, 1, 1, 1, 1, 2, 3, NA, 2, 3, 3, 4, NA, 4, 3, NA, 

         NA, 5, 5, NA, NA), .Dim = c(7L, 3L))

If you are a beginner and want to know more about R then do check out the R programming tutorial that will help you in learning R from scratch. 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...