[英]How exactly does the “group =” variable work in data.frame()
I can't find much information on exactly how the group
variable in data.frame
functions. 我找不到关于
data.frame
函数中的group
变量的确切信息。 I have three vectors as follows: 我有以下三个向量:
compare <- c("5vs2", "8vs5", "11vs8")
up <- c(4432, 1578, 2254)
down <- c(-4360, -1324, -2652)
and I am trying to create a data frame for a bar chart. 我正在尝试为条形图创建数据框。 I have created it as follows:
我创建它如下:
up_down <- data.frame(
group = c("Up", "Down"),
x = compare,
y=c(up, down))
The output dataframe is as follows: 输出数据帧如下:
group x y
1 Up 5vs2 4432
2 Down 8vs5 1578
3 Up 11vs8 2254
4 Down 5vs2 -4360
5 Up 8vs5 -1324
6 Down 11vs8 -2652
It can be seen here that in row 5, the grouping should be Down
but instead it has made it Up
. 在这里可以看到,在第5行中,分组应该为
Down
但是改为分组为Up
。 What exactly am I missing here? 我在这里到底想念什么?
Upon plotting the chart, the x values are then placed out of order, with the 11vs8 being put first, the 6vs3 second and the 9vs6 last. 在绘制图表时,然后将x值乱序放置,首先放置11vs8,其次放置6vs3,最后放置9vs6。 I feel like these should be obvious problems to solve but I can't figure them out.
我觉得这些应该是很明显的问题,但我无法解决。
ggplot(up_down, aes(x=x, y=y, fill=group))+
geom_bar(stat="identity", position="identity")
You're binding vectors of lengths 2, 3, and 6. R recycles vectors to fit the largest length, so group
is repeated 1 2 1 2 1 2
. 要绑定的长度2,3的载体,和6。R回收向量适合最大长度,所以
group
被重复1 2 1 2 1 2
。 If you want to avoid that here, try instead: group = rep(c("Up", "Down"), each = 3)
如果您想避免这种情况,请尝试:
group = rep(c("Up", "Down"), each = 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.