[R] Looping through all matrix columns each 1 row at a time

Eric Berger er|cjberger @end|ng |rom gm@||@com
Thu Apr 21 10:53:46 CEST 2022


Hi Paul,
I am not sure I understand your question, but perhaps the following is helpful.
In particular, the apply() function used with MAR=1, applies a
function to a matrix row-wise.

set.seed(123)
m <- matrix(sample(1:6,5*12,replace=TRUE),ncol=12) ## dummy data
m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    3    6    6    3    1    1    1    5    4     1     5     1
[2,]    6    3    1    3    5    6    3    1    5     2     2     6
[3,]    3    5    2    1    3    3    5    1    5     5     1     5
[4,]    2    4    3    4    2    4    4    2    3     5     1     1
[5,]    2    6    5    1    2    6    2    3    6     4     3     2

apply(m,MAR=1,function(v) length(setdiff(1:6,v))==0)

[1] FALSE FALSE FALSE FALSE  TRUE  ## only the last row has all numbers from 1-6

HTH,
Eric


On Thu, Apr 21, 2022 at 7:55 AM Paul Bernal <paulbernal07 using gmail.com> wrote:
>
> Dear R friends,
>
> One question, so, thanks to the Bert's kind feedback, I was able to create
> my matrix using the following code:
> dice_rolls = 120
> num_dice   = 1
> dice_sides = 6
>
> #performing simulation
> dice_simul = data.frame(dice(rolls = dice_rolls, ndice = num_dice, sides =
> dice_sides, plot.it = TRUE))
>
> dice_simul
>
>
> prob_matrix <- matrix(dice_simul[,1], ncol = 12, byrow = TRUE)
>
> colnames(prob_matrix) <-
> c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
>
> Now, I need to perform an analysis for each column, one row at a time. For
> example, I need to know if numbers 1 through 6 all appear in the twelve
> column for row 1, then for row 2, etc.
>
> Any guidance will be greatly appreciated.
>
> Best,
> Paul
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list