【发布时间】:2016-04-13 08:20:06
【问题描述】:
键排序是否取决于我是否首先列出要收集的列与那些不收集的列?
这是我的数据框:
library(tidyr)
wide_df <- data.frame(c("a", "b"), c("oh", "ah"), c("bla", "ble"), stringsAsFactors = FALSE)
colnames(wide_df) <- c("first", "second", "third")
wide_df
first second third
1 a oh bla
2 b ah ble
首先,我按特定顺序收集所有列,并且我的顺序在键列表中被尊重为 second, first,尽管这些列实际上是按 first, second 排序的>:
long_01_df <- gather(wide_df, my_key, my_value, second, first, third)
long_01_df
my_key my_value
1 second oh
2 second ah
3 first a
4 first b
5 third bla
6 third ble
然后我决定从收集中排除一列:
long_02_df <- gather(wide_df, my_key, my_value, second, first, -third)
long_02_df
third my_key my_value
1 bla second oh
2 ble second ah
3 bla first a
4 ble first b
键再次按第二,第一排序。然后我像这样编码,相信做同样的事情:
long_03_df <- gather(wide_df, my_key, my_value, -third, second, first)
long_03_df
我得到了根据原始data.frame中的真实列顺序排序的键:
third my_key my_value
1 bla first a
2 ble first b
3 bla second oh
4 ble second ah
当我用factor_key = TRUE 调用函数时,这种行为甚至没有改变。我错过了什么?
【问题讨论】:
-
有趣。似乎排除项应该是尾巴。也适用于
dplyr::select(iris[, 1:3], -Sepal.Length, Petal.Length, Sepal.Width)。