如何解决'x'必须是r中的数字? [英] How to solve 'x' must be numeric in r?
问题描述
我正在尝试制作直方图,但是我一直遇到错误消息.这是我的代码
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)
这是我的样品.我想创建一个直方图,y轴为0-100,x轴(安全,基本,有限等)在图中为数字(39、29、8、12、12).这有道理吗?
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
hist.default(data)中的错误:"x"必须为数字
Error in hist.default(data) : 'x' must be numeric
我做错了什么?我不知道该错误消息.
What am I doing wrong? I don't know understand the error message.
推荐答案
问题是,当它需要一个向量作为参数 hist()
函数> x (请参见?hist
).根据您编辑的帖子,您需要:
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,]))
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")
来自@ user2554330的一种简单的基本图形方法:
From @user2554330, a simpler base graphics method:
f <- as.numeric(data[1,])
names(f) <- names(data)
barplot(f)
这篇关于如何解决'x'必须是r中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!