使用 gather() 保留分组变量,同时将所有列折叠成一列

Use gather() to retain grouping variable while collapsing all columns into one column

我正在尝试将数据中的所有列收集到一个列中,但表示分组变量的列除外。例如,如果使用 mini_iris:

mini_iris <- iris[c(1, 51, 101), ]
mini_iris

这是我使用 gather() 获得的最接近结果:

mini_iris %>% gather(key = "Species", value = "Measurement")

但我想要的是让 Species 列保留原始 Species 列中的物种值。这样我仍然知道每个测量值来自哪个物种。这看起来很简单,但令人惊讶的是一直未能找到解决方案...

提前感谢您的宝贵时间。

编辑: 预期输出应如下所示:

mini_iris_long <- 
  data.frame(
    Species = c(rep("setosa", 4),rep("versicolor", 4),rep("virginica", 4)),
    Measurement = c(5.1,
                    3.5,
                    1.4,
                    0.2,
                    7.0,
                    3.2,
                    4.7,
                    1.4,
                    6.3,
                    3.3,
                    6.0,
                    2.5)
    )
mini_iris_long

根据gather,第三个参数是3个点(...)并且提到

...- A selection of columns. If empty, all variables are selected. You can supply bare variable names, select all variables between x and z with x:z, exclude y with -y. For more options, see the dplyr::select() documentation. See also the section on selection rules below.

所以我们使用-将select除'Species'之外的所有列重塑为'long'格式

library(dplyr)
library(tidyr)
mini_iris %>%
      gather(key, Measurement, -Species) %>% 
      select(-key) %>%
      arrange(Species)
#      Species Measurement
#1      setosa         5.1
#2      setosa         3.5
#3      setosa         1.4
#4      setosa         0.2
#5  versicolor         7.0
#6  versicolor         3.2
#7  versicolor         4.7
#8  versicolor         1.4
#9   virginica         6.3
#10  virginica         3.3
#11  virginica         6.0
#12  virginica         2.5

pivot_longer

mini_iris %>%
     pivot_longer(cols = -Species, values_to = 'Measurement') %>% 
     select(-name)