【问题标题】:Histogram Factor Ordering直方图因子排序
【发布时间】:2013-01-31 11:01:32
【问题描述】:

我在排序直方图的因子时遇到问题。 我的数据是这样的:

ID  onderlaag
1  strooisel
2  geen
3  strooisel
4  kniklaag
5  gras
6  geen
.
.

我已经使用 barplot() 函数制作了直方图:

条形图(table(onderlaag),ylim=c(0,250))

这里的直方图条的顺序是按字母顺序排列的,但我希望它们按以下顺序排列:strooisel - geen - gras - kniklaag。

我使用了因子函数,但在我完成此操作后,我的条形图不再有条形

onderlaag2=factor(onderlaag,levels=c("Strooisel","Geen","Gras","Kniklaag"))

我该怎么做?

【问题讨论】:

  • 如果你想要一个直方图,为什么不使用hist()
  • 这真的不是直方图,它会违反“hist”函数的预期。它只是一个有序的频率图,没有离散的、连续的 x 值集。 'barplot' 和 'table' 函数只是构建此图的一种方式(我建议先做一个聚合函数),但我认为这有点超出了问题的范围。

标签: r


【解决方案1】:

我认为您所要求的只是一种对输入进行排序的方式,我们可以很容易地将其作为您的“条形图”功能的一部分,如下所示:

barplot(table(onderlaag)[,c(4,1,2,3)], ylim=c(0,250))

“表格”功能会自动为您排序列,但之后您可以手动指定顺序。它的语法是这样的:

table(your_data)[rows_to_select, columns_to_select]

其中your_data 是要制作成表格的数据,rows_to_select 是要应用于行的过滤器列表,columns_to_select 是要应用于列的过滤器列表。通过不指定rows_to_select,我们选择了所有行,通过将columns_to_select 指定为c(4,1,2,3),我们选择了所有四列,但按特定顺序。

【讨论】:

    【解决方案2】:

    下次请通过dput提供示例数据

    # construct an example data frame similar in structure to the question
    x <- data.frame( ID = 1:4 , ord = c( 'b' , 'a' , 'b' , 'c' ) )
    
    # look at the table of x, notice it's alphabetical
    table( x )
    
    # re-order the `ord` factor levels
    levels( x$ord ) <- c( 'b' , 'a' , 'c' )
    
    # look at x
    x
    
    # look at the table of x, notice `b` now comes first
    table( x )
    
    # print the results, even though it's not a histogram  ;)
    barplot( table(x) , ylim = c( 0 , 5 ) )
    

    【讨论】:

    • 您不需要创建为“有序”。您需要做的就是按所需顺序为因子函数指定级别向量。此外, data.frame 调用创建 x$ord 作为开始的因素,因此您没有转换为因素,而是重新调整现有因素。本来可以用:levels(x$ord) &lt;- c( 'b' , 'a' , 'c' )
    • 同意.. 如果ord 是字符列,您只需要x$ord &lt;- factor( x$ord , levels = c( 'b' , 'a' , 'c' ) , ordered = TRUE )
    • 谢谢你的回答,安东尼。真的很有帮助
    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2017-07-17
    • 2014-05-19
    相关资源
    最近更新 更多