Home > other >  Using `pivot_longer with` `values_ptypes` in R
Using `pivot_longer with` `values_ptypes` in R

Time:12-31

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?

CodePudding user response:

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 
  • Related