Tienanh Nguyen Tienanh Nguyen - 1 year ago 82
R Question

Why are these 2 simple lines of code in R not working?

medals <- c(rep("United States",121), rep("China",70),rep("Great Britain",67), rep("Russia",56), rep("Germany",42), rep("France",42), rep("Japan",41 ), rep("Australia",29), rep("Italy",28), rep("Canada",22))
barplot(medals, names.arg=c("USA", "CHN", "GBR", "RUS", "GER","FRA","JPN","AUS","ITA","CAN"), main = "Top 10 Medal Winning Countries from the Rio 2016 Olympics", xlab = "Countries", ylab="Total Medals Won", cex.names=0.95)

These two lines of code are giving this error "Error in -0.01 * height : non-numeric argument to binary operator"

I'm trying to use R the first time

Answer Source

Note that barplot expects a numerical height argument, not a list of characters.



That gets you a barplot (once you have a factor it defaults to a barplot and supplies the right information). You should be able to manipulate further from there.

In fact if you investigate what plot.factor does (graphics:::plot.factor), it calls barplot(table(x),... (where x is the factor argument to plot.factor) - that's another possible avenue.

You should investigate/learn about factors, they're an important part of how R deals with categorical variables. See ?factor.

If you want to call barplot directly, you supply it with relative bar heights (i.e. the counts). One way to do that would be


(or by using table rather than summary as mentioned earlier), and then you can set the names as you were trying to before

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download