了解如何“重新排序”在R的作品 [英] Understanding how "reorder" in R works

查看:143
本文介绍了了解如何“重新排序”在R的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/tmp/thefile.csv (CSV文件)中给出以下数据:

  AA,12 
AB,1
BA,2

和以下 R 代码:

  v =读取。 csv('/ tmp / thefile.csv',header = F)
library('ggplot2')
v $ V3 = reorder(v $ V1,v $ V2)
ggplot(v, aes(x = v $ V3,y = v $ V2),stat ='identity')+ geom_bar(fill ='dark gray',stat =identity)
pre>

该图以升序显示条形图,这正是我想要的。如果没有 reorder 这一行,图表会根据因子按字母顺序显示。 然而:

 > v 
V1 V2 V3
1 AA 12 AA
2 AB 1 AB
3 BA 2 BA

显示订单仍然是按字母顺序的。如何 ggplot 知道数字顺序? 如果你看在 v $ V3 你会得到以下( print )输出:

  [1] AA AB BA 
attr(,scores)
AA AB BA
12 1 2
级别: AB BA AA

在最低一行中,您可以找到指定的层级。 b
$ b

使用级别函数可以更容易地获得此信息:

 levels(v $ V3)
[1]ABBAAA

函数 reorder 不会更改向量(或其顺序)中的值,但会设置(更改)水平分数属性来指示因子水平的顺序:

<$ p $ ($ v $ V3)
$ levels
[1]ABBAAA

$ class
[1]因素

$分数
AA AB BA
12 1 2


Given the following data in /tmp/thefile.csv (a CSV file):

AA,12
AB,1
BA,2

and the following R code:

v = read.csv('/tmp/thefile.csv', header=F)
library('ggplot2')
v$V3 = reorder(v$V1, v$V2)
ggplot(v, aes(x=v$V3, y=v$V2), stat='identity') + geom_bar(fill='dark grey', stat="identity")

The plot shows the bars in ascending order, which is what I want. Without the reorder line, the plot appears in alphabetical order according to the factor.

However:

> v
  V1  V2  V3
1 AA  12  AA
2 AB   1  AB
3 BA   2  BA

shows that the order is still alphabetical. How is ggplot aware of the numerical order?

解决方案

If you look at v$V3 you get the following (print) output:

[1] AA AB BA
attr(,"scores")
AA AB BA 
12  1  2 
Levels: AB BA AA

In the lowest line, you find the specified order of levels.

This infomation could be obtained more easily with the levels function:

levels(v$V3)
[1] "AB" "BA" "AA"

The function reorder does not change the values in the vector (or their order) but sets (changes) the levels and the scores attribute to indicate the order of factor levels:

attributes(v$V3)
$levels
[1] "AB" "BA" "AA"

$class
[1] "factor"

$scores
AA AB BA 
12  1  2 

这篇关于了解如何“重新排序”在R的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆