仅绘制二项矩阵中的1s。

huangapple go评论65阅读模式
英文:

Plot only 1s of a binomial matrix

问题

我想要绘制二项矩阵中所有1的情况(下面给出了代码)。我需要将y轴设置为频率,x轴设置为矩阵的所有列。

# 矩阵的代码
prevalence <- 0.01
Infected <- sapply(1:10, function(p) rbinom(500, 1, prevalence))

我尝试使用 hist(Infected),但这只给了我0和1的频率,没有列的详细信息。
谢谢你的帮助。

英文:

I would like to plot all the 1s of a binomial matrix (code given below). I need to histogram y-axis to be the frequency and the x-axis to be all the matrix columns.

#code for matrix    
prevalence &lt;- 0.01
Infected &lt;- sapply(1:10, function(p) rbinom(500, 1, prevalence))

I tried using hist(Infected) but this just gave me the frequency of 0 and 1, with no column details.
Thank you for your help.

答案1

得分: 3

使用 colSums 函数来获取每列中 1 的数量,然后使用 barplot 函数来生成每列的条形图。

set.seed(42)
prevalence <- 0.01
Infected <- sapply(1:10, function(p) rbinom(500, 1, prevalence))

barplot(colSums(Infected), names.arg = 1:10)

[![在此输入图像描述][1]][1]


<details>
<summary>英文:</summary>

Use `colSums` to get the number of `1` and then `barplot` to get a bar per column.

set.seed(42)
prevalence <- 0.01
Infected <- sapply(1:10, function(p) rbinom(500, 1, prevalence))

barplot(colSums(Infected), names.arg = 1:10)

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/vyxCQ.png

</details>



# 答案2
**得分**: 2

你可以尝试 `replicate` 和 `sum(rbinom(...))`, 例如,

hist(replicate(10, sum(rbinom(500, 1, 患病率))))

或者 `colSums` 

hist(colSums(matrix(rbinom(500 * 10, 1, 患病率), 10)))

你将获得类似下图的图表

[![图表描述][1]][1]

<details>
<summary>英文:</summary>

You can try `replicate` and `sum(rbinom(...))`, e.g.,

hist(replicate(10, sum(rbinom(500, 1, prevalence))))

or `colSums` 

hist(colSums(matrix(rbinom(500 * 10, 1, prevalence), 10)))

and you will obtain the plot like below

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/20WK9.png

</details>



huangapple
  • 本文由 发表于 2023年7月3日 12:17:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定