问题
I'm trying to make a histogram but I keep running into the an error message. Here is my code
library(readxl)
data <- read_excel("data.xls")
View(data)
attach(data)
names(data)
hist(data)
This is my sample. I want to create a histogram the y-axis be 0-100, x-axis (safely, basic, limited, etc) the numbers (39,29,8,12,12) be in the graph. Does this help make sense?
Safely Basic Limited Unimproved Open
39 29 8 12 12
Error in hist.default(data) : 'x' must be numeric
What am I doing wrong? I don't know understand the error message.
回答1:
The issue is that you are passing a dataframe to the hist()
function, when it requires a vector for its argument x
(see ?hist
). Based on your edited post, you would want:
hist(as.numeric(data[1,]))
Where data[1,]
creates a vector from the first row of your dataframe.
Though it seems like you may actually be looking for a bar plot. In that case, try:
plot_data <- data.frame(t(data)) %>%
tibble::rownames_to_column()
ggplot(plot_data,aes(x = rowname,y=t.data.)) +
stat_identity(geom = "bar")
From @user2554330, a simpler base graphics method:
f <- as.numeric(data[1,])
names(f) <- names(data)
barplot(f)
回答2:
In your case data
is not a variable, but a dataframe that contains variables.
You can take the histogram of each single variable like this:
library(readxl)
data <- read_excel("data.xls")
If you want to look at the histogram of variable Safely
:
hist(data$Safely)
You can access each variable contained in data
in the same way.
来源:https://stackoverflow.com/questions/55592116/how-to-solve-x-must-be-numeric-in-r