Umer Daraz
Umer Daraz

Reputation: 1

how to count the some fixed values in each row of a matrix and the different columns of all possible pairs of two rows of a matrix in R

I have a matrix and I want to count the some fixed values (i) in each row and (ii) each column of two rows of a matrix by using the loop command. kindly check the attached files and explanations are given in these files. . thank you so much in advance.

for example, A=matrix(c(0,1,2,1,1,0,2,0,1),3,3). n=3 number of columns. N=3 number of rows. ro= how many times 1 occur in each row.

for example in first row 1 occur once time, in second row 1 occur two times and in third row 1 occur again once time. so, sum(ro) = 4. r1= n-ro. total remaining values in each row. for example in first row r1= 2 because two values 0 and 2 are remaining values. in second row the remaining values is only 0 so r1 = 1 for second row.

now I want to count the some fixed values in each columns of two rows. r11 = (1,1) it means that i want to check the this fixed value is occurred between the columns of two rows or not. also, roo = (0,0) and (2,2), ro2 = (0,2),(2,0). ro1 = (1,0),(0,1),(1,2), (2,1). then at the end i want to calculate this expression. Thank you so much in advance. B(k)= sum(a start from 1 to N)(ro^4-ro^3-ror1)-sum(a not equal to b)roo*ro2(ro2(72ro2-99)-roo(81ro2-45)+68)

Upvotes: 0

Views: 80

Answers (1)

akrun
akrun

Reputation: 887291

We can use rowSums on a logical matrixx

ro <- rowSums(A == 1)
ro
[1] 1 2 1

Then do the subtraction from the number of columns of the matrix

ncol(A) - ro
[1] 2 1 2

The last part of the question is not clear. May be this helps

library(stringr)
v1 <- do.call(paste, c(as.data.frame(A), sep=""))
str_count(v1, "01")
#[1] 1 0 1
str_count(v1, "12")
#[1] 1 0 0

Upvotes: 1

Related Questions