1

I want to pivot_longer() my data frame to contain a column with the row number of the original data. Consider the following data frame:

set.seed(0)

df <- data.frame(
  a = runif(3),
  b = runif(3),
  c = runif(3)
) %>% mutate("row_id" = row_number())


> df
          a         b         c row_id
1 0.8966972 0.5728534 0.8983897      1
2 0.2655087 0.9082078 0.9446753      2
3 0.3721239 0.2016819 0.6607978      3

The desired output should look like this:

   name   value  row_id
   <chr>  <dbl>  <int>
 1 a      0.897  1
 2 b      0.573  1
 3 c      0.898  1
 4 a      0.266  2
 5 b      0.908  2
 6 c      0.945  2
 7 a      0.372  3
 8 b      0.202  3
 9 c      0.661  3

After reading ?pivot_longer I tried to accomplish this by specifying names_pattern and names_to in the following way:

result <- df %>% tidyr::pivot_longer(
  cols = everything(),
  names_to = c(".value", "row_id"),
  names_pattern = "(.)([row_id])"
)

But end up with an output I don't really understand:

# A tibble: 6 x 2
  row_id     r
  <chr>  <int>
1 NA        NA
2 o          1
3 NA        NA
4 o          2
5 NA        NA
6 o          3

I thought [row_id] should define a column by it's literal name. What am I doing wrong? Thanks

zx8754
  • 52,746
  • 12
  • 114
  • 209
Comfort Eagle
  • 2,112
  • 2
  • 22
  • 44

1 Answers1

2

We don't need to specify the pattern here. Just use the cols to select or deselect (-). In this case, it makes more sense to deselect the 'row_id'

library(dplyr)
library(tidyr)
df %>% 
   pivot_longer(cols = -row_id)

It can also be written as

df %>% 
    pivot_longer(cols = a:c)

Or a regex pattern as name with matches or some of the select_helpers

df %>%
   pivot_longer(cols= matches('^[a-c]$'))
akrun
  • 874,273
  • 37
  • 540
  • 662