Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot_longer on integer and factor

Tags:

r

pivot

tidyr

I have a dataset that looks like the following.

# A tibble: 1 x 4
  hhm1q001 hhm2q001 hhm1q002 hhm2q002
  <chr>    <chr>    <int>    <int>   
1 blue     red      30       50 

I have been trying to transform it to long using tidyr::pivot_longer my expected output looks like this:

  hhm   q001  q002 
  <int> <chr> <int>
1 1     blue  30   
2 2     red   50

I have tried the following code

HHS_long <- pivot_longer(HHS_all, 
                         cols= starts_with("hhm"), #identifies the column from which to go from wide to long
                         names_to = ("hhm"), #name(s) of new column(s) created from cols= 
                         values_drop_na = FALSE
)
head(HHS_long)   

Unfortunately i get the following error .Error: No common type for hhm1q101 <factor<b5064>> and hhm1q102 <integer>.

Not sure how to go around this, i get they are not the same class, but i have quite a lot of variable in the dataset and they are definitely of a different class. Hope this is the correct format to posting.

Thanks for any help

like image 335
anatase Avatar asked Jun 24 '26 03:06

anatase


1 Answers

I struggle a little bit when I use the new pivot_longer. Sometimes, I feel that renaming variable names before pivot_longer could make it much easier:

library(tidyverse)
HHS_all <- data.frame(hhm1q001 =  "blue", hhm2q001 =  "red", hhm1q002 = 30, hhm2q002 = 50)

df <- HHS_all %>% 
  rename(q001hhm1 = hhm1q001, q001hhm2 = hhm2q001, 
         q002hhm1 = hhm1q002, q002hhm2 = hhm2q002) 

df %>%
  pivot_longer(everything(), names_to = c(".value", "hhm"), names_sep = "hhm")
# A tibble: 2 x 3
  hhm   q001   q002
  <chr> <fct> <dbl>
1 1     blue     30
2 2     red      50
like image 125
Zhiqiang Wang Avatar answered Jun 25 '26 20:06

Zhiqiang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!