本文介绍了在R Studio中使用Barplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用此代码进行barplot时(例如, L $ neighbourhood 是巴黎的公寓社区,例如Champs-Elysées,Batignolles(它是字符串数据)和 L $ price是公寓价格的数字数据).

when I try this code for barplot (L$neighbourhood is the apartment neighbourhood in Paris for example, Champs-Elysées, Batignolles, which is string data, and L$price is the numeric data for apartment price).

 barplot(L$neighbourhood, L$price, main = "TITLE", xlab = "Neighbourhood", ylab = "Price")

但是,我得到一个错误:

But, I get an error:

我们不能在R的barplot函数中使用字符串数据作为输入吗?我该如何解决该错误?

We cannot use string data as an input in barplot function in R? How can I fix this error please?

所有街区

推荐答案

不清楚要绘制的内容.假设您要查看每个邻域的平均价格.如果您要这样做的话,您可以像这样继续进行.

Quite unclear what you want to barplot. Let's assume you want to see the average price per neighborhood. If that's what you're after you can proceed like this.

首先提供一些说明性数据:

First some illustrative data:

set.seed(123)
Neighborhood <- sample(LETTERS[1:4], 10, replace = T)
Price <- sample(10:100, 10, replace = T)
df <- data.frame(Neighborhood, Price)
df
   Neighborhood Price
1             C    23
2             C    34
3             C    99
4             B   100
5             C    78
6             B   100
7             B    66
8             B    18
9             C    81
10            A    35

现在使用函数 aggregate 按邻域计算平均值,并将结果存储在新的数据框中:

Now compute the averages by neighborhood using the function aggregate and store the result in a new dataframe:

df_new <- aggregate(x = df$Price, by = list(df$Neighborhood), function(x) mean(x))
df_new
  Group.1  x
1       A 35
2       B 71
3       C 63

最后,您可以在变量 x 中绘制平均价格,并从 Group.1 列添加邻域名称:

And finally you can plot the average prices in variable x and add the neighborhood names from the Group.1column:

barplot(df_new$x, names.arg = df_new$Group.1)

一个更简单的解决方案是使用 tapply mean :

An even simpler solution is this, using tapplyand mean:

df_new <- tapply(df$Price, df$Neighborhood, mean)
barplot(df_new, names.arg = names(df_new))

这篇关于在R Studio中使用Barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:40