Using barplot in R studio

*爱你&永不变心* 提交于 2020-01-16 07:49:33

问题


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:

Error in barplot.default(L$neighbourhood, L$price, main = "TITLE", xlab = "Neighbourhood", : 'height' must be a vector or a matrix

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

allneighbourhoods


回答1:


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

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

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)

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))


来源:https://stackoverflow.com/questions/59668110/using-barplot-in-r-studio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!