Home > other >  How to make a list of proportion tables relative to each row?
How to make a list of proportion tables relative to each row?

Time:11-08

I have this dataset and list of dataframe matrixes as follows :

set.seed(222)
df = data.frame(x = trunc(runif(10,0,2)),
                y = trunc(runif(10,4,6)),
                z = trunc(runif(10,19,21)),
                m = trunc(runif(10,28,30)))
df


t1 = table(df$x,df$y)
t2=table(df$z,df$m)


L = list(t1,t2)

L1 <- lapply(L, as.data.frame.matrix)

The output is

[[1]]
  4 5
0 4 2
1 3 1

[[2]]
   28 29
19  3  2
20  1  4

I wish to create proportion tables as for example for the first elements :

[[1]]
  4 5
0 4/(4 2) 2/(4 2)
1 3/(3 1) 1/(3 1)

Thank you

CodePudding user response:

We can use sapply to iterate over elements in L1, obtain rowSums and get proportions.

  sapply(L1, function(x) {
  tmp <- x[1, ]
  tmp <- tmp/rowSums(tmp)
  tmp
})
 [,1]      [,2]
4 0.6666667 0.6 
5 0.3333333 0.4 

CodePudding user response:

We may use proportions

 sapply(L1, \(x) proportions(as.matrix(x), 1)[1,])
       [,1] [,2]
4 0.6666667  0.6
5 0.3333333  0.4
  • Related