28

我有一个这种格式的数据文件:

Weight    Industry Type  
251,787   Kellogg  h  
253,9601  Kellogg  a  
256,0758  Kellogg  h  
....

我读取数据并尝试使用以下命令绘制直方图:

 ce <- read.table("file.txt", header = TRUE)

 we = ce[,1]
 in = ce[,2]
 ty = ce[,3]

hist(we)

但我得到这个错误:

错误 en hist.default(we) : 'x' 必须是数字。

我需要做什么才能为我的三个变量绘制直方图?

4

3 回答 3

24

由于千位分隔符,数据将被读取为“非数字”。所以你需要转换它:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

现在你可以做

 hist(we)

和其他数字运算。

于 2010-02-27T23:06:33.767 回答
5

请注意,您也可以ce使用列名直接从(在逗号删除之后)绘制:

hist(ce$Weight)

(与 using 相反hist(ce[1]),这将导致相同的“必须是数字”错误。)

这也适用于数据库查询结果。

于 2012-05-25T18:20:10.190 回答
3

使用dec参数通过添加以下内容设置","为小数点:

 ce <- read.table("file.txt", header = TRUE, dec = ",")
于 2013-02-20T21:42:39.240 回答