1

My question is simple:

I've been trying to use pivot_longer with values_ptypes:

This is my code:

df <-mtcars %>% rownames_to_column()
df[1,] %>% pivot_longer(everything(),names_to = 'My Values', values_ptypes = list(rowname = 'character'))

df[1,] %>% pivot_longer(everything(),names_to = 'My Values', values_ptypes = list(rowname = as.character))

I have this message: Error: Can't combine rowname <character> and mpg <double>.

The idea of values_ptypes is warning pivot_longer that I have a column that is a character, right?

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Laura
  • 675
  • 10
  • 32
  • Your sugestion works @akrun thanks, again. How can do this using `pivot_longer` and `values_ptypes` argument? – Laura Dec 30 '21 at 21:52
  • Following your suggestion, after pivot_longer I will have to use mutate again to change to double, right? – Laura Dec 30 '21 at 21:53
  • I see @akrun. Thanks again! Have a great new year! – Laura Dec 30 '21 at 21:57
  • 1
    what you are looking for is more or less `df[1,] %>% pivot_longer(everything(),names_to = 'My Values', values_transform = list(value = as.character))` – Onyambu Dec 30 '21 at 22:00

1 Answers1

2

TL;DR: Change values_ptypes to values_transform if you want to transform the class of your variables when pivoting.


So first, you get the error not because values_ptypes is misspecified, but because you are trying to put numeric and character values into one column, and tidyr doesn't know how to:

library(dplyr)

df <- mtcars %>% tibble::rownames_to_column()

df[1, c(1:2)] %>% 
  tidyr::pivot_longer(
    everything(),
    names_to = 'My Values'
  )

# > Error: Can't combine `rowname` <character> and `mpg` <double>.

Second: values_ptypes is used to confirm that your values are as expected, not to change them.

Fix

As @Onyambu commented, if you want to change your values you can use values_transform:

df[1, ] %>% 
  tidyr::pivot_longer(
    everything(),
    names_to = 'My Values',
    values_transform = list(value = as.character)
  )

Result:

# A tibble: 12 x 2
   `My Values` value    
   <chr>       <chr>    
 1 rowname     Mazda RX4
 2 mpg         21       
 3 cyl         6        
 4 disp        160      
 5 hp          110      
 6 drat        3.9      
 7 wt          2.62     
 8 qsec        16.46    
 9 vs          0        
10 am          1        
11 gear        4        
12 carb        4 
jpiversen
  • 3,062
  • 1
  • 8
  • 12
  • 1
    No need of the mutate function. Check my comment – Onyambu Dec 30 '21 at 22:05
  • 1
    Just do `df[1,] %>% pivot_longer(everything(),names_to = 'My Values', values_transform = list(value = as.character))` – Onyambu Dec 30 '21 at 22:05
  • Oh, you're right! I tried that, but I misspelled `value` as `values`. Such a simple mistake. I'll change my answer and credit you. – jpiversen Dec 30 '21 at 22:08