0

I am trying to gather all of the columns in my data into a single column, except for one column that represents a grouping variable. For example, if using mini_iris:

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

This is the closest I was able to get using gather():

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

But what I want is for the Species column to retain the species values from the original Species column. This way I still know which Species each measurement came from. This seems pretty simple but haven't been able to find a solution amazingly...

Thank you in advance for your time.

EDIT: The expected output should look like this:

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
mvanaman
  • 171
  • 11

1 Answers1

0

According to gather, the third argument is 3 dots (...) and it is mentioned that

...- 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.

So we use - to select all columns except the 'Species' to be reshaped into 'long' format

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

Or with pivot_longer

mini_iris %>%
     pivot_longer(cols = -Species, values_to = 'Measurement') %>% 
     select(-name)
akrun
  • 874,273
  • 37
  • 540
  • 662