Search code examples
rapplysapply

apply or loop rbeta using different alpha and beta values from a dataframe in R


I'm trying to use sapply to create a matrix that contains output from rbeta using different specified alphas and betas obtained from a dataset. I think this should be fairly simple, but I am struggling.

Here is some data

q1 <- c(27, 104)
q2 <- c(25, 121)
q3 <- c(29, 114)
df <- as.data.frame(rbind(q1,q2,q3))
colnames(df) <- c('alpha','beta')

This is what I've done. Which is giving me 3 separate rbeta samples but I don't think its taking the correct values by row. E.g. the first rbeta should be: rbeta(I, 27, 104)

I=10
rb <- sapply(1:3, function(x) rbeta(I, df$alpha, df$beta))

Can someone please clarify what I'm doing wrong here or point me in another direction?


Solution

  • Using apply on rows

    set.seed(42)
    apply(df, 1, function(x) rbeta(I, x["alpha"], x["beta"]))
                 q1        q2        q3
     [1,] 0.1841086 0.1242001 0.1931461
     [2,] 0.2211195 0.1615636 0.2210664
     [3,] 0.2331062 0.1665653 0.1790950
     [4,] 0.2228934 0.1953668 0.2208726
     [5,] 0.2018876 0.1613773 0.2316363
     [6,] 0.2807989 0.2275919 0.2472799
     [7,] 0.2023407 0.1606147 0.1802312
     [8,] 0.3175574 0.1652301 0.2229498
     [9,] 0.2036065 0.2220179 0.1385964
    [10,] 0.2680387 0.1564213 0.1738062
    

    or using Vectorize

    set.seed(42)
    Vectorize(rbeta)(I, df$alpha, df$beta)
               [,1]      [,2]      [,3]
     [1,] 0.1841086 0.1242001 0.1931461
     [2,] 0.2211195 0.1615636 0.2210664
     [3,] 0.2331062 0.1665653 0.1790950
     [4,] 0.2228934 0.1953668 0.2208726
     [5,] 0.2018876 0.1613773 0.2316363
     [6,] 0.2807989 0.2275919 0.2472799
     [7,] 0.2023407 0.1606147 0.1802312
     [8,] 0.3175574 0.1652301 0.2229498
     [9,] 0.2036065 0.2220179 0.1385964
    [10,] 0.2680387 0.1564213 0.1738062