BNS1993 - 9 months ago 32

R Question

I have a matrix like this one.

```

a b c d

[1,] 1 0 0 0

[2,] 1 0 0 0

[3,] 1 0 0 0

[4,] 1 0 0 0

[5,] 1 0 0 0

[6,] 1 0 0 0

[7,] 1 0 0 0

[8,] 1 1 0 0

[9,] 1 1 0 0

[10,] 1 1 0 0

[11,] 0 1 0 1

[12,] 1 1 0 1

[13,] 1 1 0 1

[14,] 1 1 0 1

[15,] 0 1 0 1

[16,] 0 1 0 1

[17,] 0 1 0 1

[18,] 0 1 0 1

[19,] 0 1 1 0

[20,] 0 1 0 0

[21,] 1 1 1 1

[22,] 1 1 1 1

[23,] 1 0 1 1

[24,] 1 0 0 1

[25,] 1 0 0 1

[26,] 1 0 1 1

[27,] 1 0 1 0

[28,] 0 0 1 0

[29,] 0 0 1 0

[30,] 0 0 1 1`

code for reproducing:

```

mat1 <- as.matrix(cbind(c(rep(1,10),0,1,1,1,0,rep(0,5),rep(1,7),0,0,0),c(rep(0,7),rep(1,15),rep(0,8)),c(rep(0,18),1,0,1,1,1,0,0,rep(1,5)),c(rep(0,10),rep(1,6),1,1,0,0,rep(1,6),0,0,0,1)))

colnames(mat1) <- c("a", "b", "c", "d")

What I want is to check in each row if there are more then one values of 1. Like the first row for example row 8:

```

a b c d

[8,] 1 1 0 0`

Then I want to replace these 1 values for their corresponding column name.

Like this:

`'`

a b c d

[8,] a b 0 0`

'

I want to apply this to all 1 values in rows where there is more then one 1 value, while keeping the matrix structure.

Selecting the rows with more then one 1 value was not that hard, selecting the corresponding column names was also manageable, but then replacing them, I could not manage.

This is what I have managed to do

```

apply(mat1,1, function(x) {

#select rows with more then one 1

if(sum(x) > 1) {

#for every row with more than one 1; check if the value is 1

for (i in 1:4) {

if (x[i]==1) {

#this seems to print every column name I need

print(colnames(mat1)[i])

#replacing should happen here I ques, but I can't get the location in the matrix.

}

}

}

})

`

Would anyone be so kind to help me with this problem? Also, a better way than this double loop is welcome of course, but not necessary for my problem.

Answer Source

You can try this:

```
col_n <- colnames(mat1)
res <- apply(mat1,1, function(x) {
#select rows with more then one 1
if(sum(x) > 1) {
x[x == 1] <- col_n[x == 1]
}
return(x)
})
res <- t(res)
```