如何在R数据框中查找列中特定值的百分比

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

How to find percent of certain values along columns in R dataframe

问题

  1. 假设我在许多列中有诸如“是”或“否”之类的分类值,我想要每列回答“是”的百分比,并使用条形图进行可视化。我可以编写如下所示的R代码来实现这个目的。
  2. ```R
  3. data <- read.table(text=
  4. "Q1 Q2 Q3 Q4
  5. 0 1 0 1
  6. 0 1 0 1
  7. 1 1 1 1
  8. 1 0 1 0
  9. 0 0 0 0
  10. 1 1 0 1", header=TRUE)

从上表中,我需要每列回答“是”的百分比(是=1,否=0)。然后我想用R的条形图可视化所有列的百分比值。请指导我如何编写代码。

作为一个初学者,我完全没有头绪。我该如何做呢?

  1. <details>
  2. <summary>英文:</summary>
  3. Suppose I have categorical values such as Yes or No in a number of columns, I want % of each column responding &quot;yes&quot; with a barplot. How I can be able to write code for R is shown below, showing what I need.

data <- read.table(text=
"Q1 Q2 Q3 Q4
0 1 0 1
0 1 0 1
1 1 1 1
1 0 1 0
0 0 0 0
1 1 0 1", header=TRUE)

  1. From the above table, I need % of each column responding yes (Yes=1, No=0) and with that percent values of all columns I want to visualize with a barplot in R. Please, guide me through the code.
  2. As a beginner I am getting no idea at all. How to do this.
  3. </details>
  4. # 答案1
  5. **得分**: 2
  6. ```r
  7. # 计算每列的“是”(1)的百分比
  8. percentage_yes <- colMeans(data) * 100
  9. # 创建条形图
  10. barplot(percentage_yes, names.arg = colnames(data), ylab = "百分比(%)", main = "“是”回答的百分比")
英文:

Could you please check the below output

  1. # Calculate the percentage of &quot;yes&quot; (1) for each column
  2. percentage_yes &lt;- colMeans(data) * 100
  3. # Create a bar plot
  4. barplot(percentage_yes, names.arg = colnames(data), ylab = &quot;Percentage (%)&quot;, main = &quot;Percentage of &#39;Yes&#39; Responses&quot;)

如何在R数据框中查找列中特定值的百分比

huangapple
  • 本文由 发表于 2023年8月9日 11:54:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864466-2.html
匿名

发表评论

匿名网友

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

确定