R:使用ggplot2绘制%直方图不适用于字母数字并将freq转换为freq%

时间:2017-09-15 20:15:53

标签: r

这是我在CSV文件中设置的数据

Weight   Count
Less than 500 grams 5,980
500 to 999 grams    22,015
1,000 to 1,499 grams    29,846
1,500 to 1,999 grams    63,427
2,000 to 2,499 grams    204,295
2,500 to 2,999 grams    744,181
 3,000 to 3,499 grams   1,566,755
 3,500 to 3,999 grams   1,055,004
 4,000 to 4,499 grams   262,997
 4,500 to 4,999 grams   36,706
 5,000 to 5,499 grams   4,216

我试图使用频率%制作直方图但是,我遇到了两个问题

1)由于字母数字文本,$ Weight被认为是一个因子而不是数字。我似乎无法找到一种方法让R中设​​置的范围全部为数字,因此ggplot将接受范围。什么是最好的方法呢?

编辑:我尝试使用cut()设置间隔,但由于原始数据是字母数字,因此无法正常工作。我收到错误

newborn$Weight_cut<- cut(newborn$Weight, 
                       breaks = c(0, 500, 1000,1500,2000,2500,3000,3500,4000,4500,5000), 
                       labels = c("<500","500-999",
                                  "1000-1499","1500-1999",
                                  "2000-2499","2500-2999",
                                  "3000-3499","3500-3999",
                                  "4000-4499","4500-4999",
                                  "5000-5499"), 
                       right = FALSE)
Error in cut.default(newborn$Weight, breaks = c(0, 500, 1000, 1500, 2000,  : 
  'x' must be numeric

2)因为我需要绘制%freq而不是count我尝试使用%freq创建一个新列,但是R正在读取$ Count作为因子,所以这是我试过的代码...但它然后改变我所有的计数数字并使频率完全错误

> class(newborn$Count)
[1] "factor"
> newborn$Count <- as.numeric(newborn$Count)
> class(newborn$Count)
[1] "numeric"
> newborn$Percent = newborn$Count/sum(newborn$Count)*100
> newborn$Percent
 [1] 13.636364  6.060606  9.090909 15.151515  4.545455 16.666667  3.030303  1.515152  7.575758 10.606061 12.121212
> newborn
                  Weight Count   Percent
1    Less than 500 grams     9 13.636364
2       500 to 999 grams     4  6.060606
3   1,000 to 1,499 grams     6  9.090909
4   1,500 to 1,999 grams    10 15.151515
5   2,000 to 2,499 grams     3  4.545455
6   2,500 to 2,999 grams    11 16.666667
7   3,000 to 3,499 grams     2  3.030303
8   3,500 to 3,999 grams     1  1.515152
9   4,000 to 4,499 grams     5  7.575758
10  4,500 to 4,999 grams     7 10.606061
11  5,000 to 5,499 grams     8 12.121212

0 个答案:

没有答案