Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R data.table calculate sum of other rows

Using R and data.table I’ve got this data

test = data.frame(genotypes =  c('A|A', 'A|G', 'G|G'), high = c(73, 113, 87), low = c(77, 155, 63))
genotypes high low
1       A|A   73  77
2       A|G  113 155
3       G|G   87  63

How can I get 3 new matrix of this data, containing 1 row and the sum of other rows by columns?

# low           |   high
# -----------------------------
# A|A           |   A|A
# -----------------------------
# A|G + G|G     |   A|G + G|G

So I need to get nrow(test) adiitional matrix in next view:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

matrix(c(73, 113+87, 77, 155+63), nrow = 2)
matrix(c(113, 73+87, 155, 77+63), nrow = 2)
matrix(c(87, 73+113, 63, 77+155), nrow = 2)

example

> matrix(c(73, 113+87, 77, 155+63), nrow = 2)
     [,1] [,2]
[1,]   73   77
[2,]  200  218

How can do that?

>Solution :

cols = c('high', 'low')
lapply(
  seq_len(nrow(df)), 
  \(i) matrix(c(unlist(df[i, cols]), colSums(df[-i, cols])), nrow = 2, byrow=TRUE)
)

[[1]]
     [,1] [,2]
[1,]   73   77
[2,]  200  218

[[2]]
     [,1] [,2]
[1,]  113  155
[2,]  160  140

[[3]]
     [,1] [,2]
[1,]   87   63
[2,]  186  232

Data

df = data.frame(genotypes =  c('A|A', 'A|G', 'G|G'), high = c(73, 113, 87), low = c(77, 155, 63))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading