user 31466
user 31466

Reputation: 699

Creating a square matrix whose elements is 1 with certain condition and 0 otherwise

Consider the data frame:

set.seed(1234)
n = 10
dat <- data.frame(x=runif(n,0,200), d=rbinom(n,1,.5))

Now I want to crate a matrix a with n by n dimension whose element a[i,j]=1 , if (dat[j,1]==x[i]& dat[j,2]==1), and 0 otherwise.

The following codes work correctly:

a <- matrix(,ncol=n, nrow=n)

for(i in 1:n){
  a[i,] <- (dat$x==dat$x[i] & dat$d==1)
}

But is there a way to create the a variable with outer() or similar other function?

Upvotes: 1

Views: 144

Answers (2)

akrun
akrun

Reputation: 886948

Here is another vectorized option

a <- matrix(FALSE,ncol=n, nrow=n)
a[row(a)==col(a)] <- dat$d==1

Upvotes: 1

mtoto
mtoto

Reputation: 24178

You could use diag(), to convert dat$x to the diagonal of a matrix. We add the logical condition "==1" to turn the binary matrix into a boolean one.

diag(dat$d)==1 

Upvotes: 4

Related Questions