简体   繁体   中英

R:Calculating percentage values across a matrix based on the values in another matrix

I have two matrices, one is a 10x1 double matrix, that can be expanded to any user preset number, eg. 100.

View(min_matrx)

    V1
1   27
2   46
3   30
4   59
5   46
6   45
7   34
8   31
9   52
10  46

The other matrix looks like this, there are more rows not shown:

View(main_matrx)

row.names     sum_value
s17           45
s7469         213
s20984        24
s17309        214
s7432369      43
s221320984    12
s17556        34
s741269       11
s20132984     35

For each row name in main_matrx I want to count the number of times that a value more than the sum_value in main_matrx appears in min_matrx. Then I want to divide that by the number of rows in min_matrx and add that value as a new column in main_matrx.

For example, in row 1 of main_matrx for s17, the number of times a value appears that is more than 45 in min_matrx =5 times.

Now divide that 5 by 10 rows of min_matrx=> 5/10 =0.5 would be the value I'd like to have as a new column in main_matrx for s17. Then the same formula for all the s_ids in the row names.

So far I have fiddled with:

for(s in 1:length(main_matrx)) {
  new<-sum(main_matrx[s,]>min_CPRS_set)/length(min_matrx)
  }

and I tried using apply() but I'm still not getting results.

apply(main_matrx,1:length(main_matrx), function(x) sum(main_matrx>min_CPRS_set)/length(min_matrx)))

Now, I'm just stuck because it's not working. I'm still new to R so my code isn't particularly efficient. Any suggestions?

Lots of ways to approach this. Here's one that came to my head (I think I understand what you're after; again it's much easier to understand an example than with words alone. In the future I'd suggest an example to accompany the text question.)

Where x is an element, y is a vector

FUN <- function(x, y = min_matrix[, 1]) { 
    sum(y > x)/length(y)
}
main_matrx$new <- sapply(main_matrx[, 2], FUN)

## > main_matrx
##    row.names sum_value new
## 1        s17        45 0.5
## 2      s7469       213 0.0
## 3     s20984        24 1.0
## 4     s17309       214 0.0
## 5   s7432369        43 0.6
## 6 s221320984        12 1.0
## 7     s17556        34 0.6
## 8    s741269        11 1.0
## 9  s20132984        35 0.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM