英文:
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 "yes" 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 "yes" (1) for each column
percentage_yes <- colMeans(data) * 100
# Create a bar plot
barplot(percentage_yes, names.arg = colnames(data), ylab = "Percentage (%)", main = "Percentage of 'Yes' Responses")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论