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

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

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

问题

假设我在许多列中有诸如“是”或“否”之类的分类值,我想要每列回答“是”的百分比,并使用条形图进行可视化。我可以编写如下所示的R代码来实现这个目的。

```R
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,否=0)。然后我想用R的条形图可视化所有列的百分比值。请指导我如何编写代码。

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


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

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)


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. 

As a beginner I am getting no idea at all. How to do this. 

</details>


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

```r
# 计算每列的“是”(1)的百分比
percentage_yes <- colMeans(data) * 100

# 创建条形图
barplot(percentage_yes, names.arg = colnames(data), ylab = "百分比(%)", main = "“是”回答的百分比")
英文:

Could you please check the below output

# Calculate the percentage of &quot;yes&quot; (1) for each column
percentage_yes &lt;- colMeans(data) * 100

# Create a bar plot
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:

确定