英文:
How to find percent of certain values along columns in R dataframe
问题
假设我有一些列中的分类值,例如"Yes"或"No",我想要每列中回答"yes"的百分比,并用条形图进行可视化。下面是我在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)
# 计算每列中回答"yes"的百分比
percent_yes <- colMeans(data == 1) * 100
# 使用条形图可视化百分比值
barplot(percent_yes, names.arg = colnames(data), xlab = "Columns", ylab = "Percentage of Yes")
以上代码中,首先我们读取了数据并存储在data
变量中。然后,我们使用colMeans
函数计算了每列中回答"yes"的百分比,并将结果乘以100以得到百分比值。最后,我们使用barplot
函数将百分比值以条形图的形式进行可视化,其中names.arg
参数用于指定每个条形的名称,xlab
参数用于设置x轴标签,ylab
参数用于设置y轴标签。
希望这能帮到你!如果你有任何进一步的问题,请随时问我。
英文:
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.
答案1
得分: 2
请你检查下面的输出
# 计算每列中“是”(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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论