Meaning of ".value" in pivot_longer

Hi,

I have read the definition but still a bit difficult to wrap my head a round it:

Maybe somebody could explain in simpler language, thank you.

I like to learn and teach with concrete examples; I adapted this from the example in ?pivot_longer (the last one down at the bottom)

library(tidyverse)
(a3 <- head(anscombe,3)) 


a3 %>%
  pivot_longer(
    everything(),
    names_to = c("charpart", "numpart"),
    names_pattern = "(.)(.)"
  )

a3 %>%
  pivot_longer(
    everything(),
    names_to = c(".value", "numpart"),
    names_pattern = "(.)(.)"
  )

so we start with

  x1 x2 x3 x4   y1   y2    y3   y4
1 10 10 10  8 8.04 9.14  7.46 6.58
2  8  8  8  8 6.95 8.14  6.77 5.76
3 13 13 13  8 7.58 8.74 12.74 7.71

you can see its wide; it has columns with pattern in their name; a letter, a number.
if you just make it long like the first typical pattern you might split the character part from the number part

# A tibble: 24 × 3
   charpart numpart value
   <chr>    <chr>   <dbl>
 1 x        1       10   
 2 x        2       10   
 3 x        3       10   
 4 x        4        8   
 5 y        1        8.04
 6 y        2        9.14
 7 y        3        7.46
 8 y        4        6.58
 9 x        1        8   
10 x        2        8   

but if you had used the .value it would make columns from that character symbol (x,y)

 A tibble: 12 × 3
   numpart     x     y
   <chr>   <dbl> <dbl>
 1 1          10  8.04
 2 2          10  9.14
 3 3          10  7.46
 4 4           8  6.58
 5 1           8  6.95
 6 2           8  8.14
 7 3           8  6.77
 8 4           8  5.76
 9 1          13  7.58
10 2          13  8.74
11 3          13 12.7 
12 4           8  7.71

this has effectively saved you from pivot_longer then pivot_wider; by just doing it in a single pivot_longer where the x/y columns to put values into was determined by the .value name which matched the regex for the x.y part.

5 Likes

I am very grateful for this, thank you, this is very didactic. I will read carefully and come back with questions if I may.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.