Home > Software engineering >  pivot_wider not giving desired output
pivot_wider not giving desired output

Time:01-03

I'm trying to get Hugo_Symbol as columns and each sample as row. but seem I'm not doing it right. could you please help?

data looks like this

library(tidyverse)
df <- data.frame(Hugo_Symbol = paste0(rep("Gene", 10), seq(1,10)),
          sample_A = runif(10),
          sample_B = runif(10),
          sample_C = runif(10),
          sample_D = runif(10))

#my implementation of pivot wider

df %>% pivot_wider(names_from=Hugo_Symbol, 
            values_from=c(sample_A ,sample_B ,sample_C, sample_D))

CodePudding user response:

First pivot longer to move samples from columns to rows, then pivot wider to move Hugo_Symbol from rows to columns:

library(tidyr)

df %>% 
  pivot_longer(!Hugo_Symbol, names_to = "Sample") %>%
  pivot_wider(names_from = Hugo_Symbol)
# A tibble: 4 × 11
  Sample   Gene1  Gene2 Gene3 Gene4 Gene5 Gene6 Gene7 Gene8 Gene9 Gene10
  <chr>    <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
1 sample_A 0.988 0.434  0.296 0.262 0.720 0.266 0.952 0.215 0.908 0.215 
2 sample_B 0.817 0.0590 0.909 0.192 0.296 0.186 0.162 0.586 0.465 0.0446
3 sample_C 0.104 0.0404 0.119 0.783 0.995 0.747 0.481 0.197 0.392 0.633 
4 sample_D 0.816 0.917  0.368 0.408 0.879 0.590 0.249 0.352 0.142 0.990 

CodePudding user response:

Try with data.table::transpose

data.table::transpose(df, make.names = 'Hugo_Symbol', keep.names = "Sample")

-output

 Sample      Gene1      Gene2      Gene3      Gene4     Gene5     Gene6     Gene7     Gene8     Gene9     Gene10
1 sample_A 0.45562285 0.72161304 0.50670439 0.45098018 0.3326703 0.1136692 0.4864477 0.3572497 0.4592931 0.39923991
2 sample_B 0.42476644 0.74091315 0.68306540 0.47477612 0.8888358 0.8132895 0.3736354 0.5468712 0.6252278 0.50924528
3 sample_C 0.07040627 0.35013810 0.08963303 0.03448959 0.5425005 0.9986051 0.2445660 0.5075495 0.9698232 0.80432695
4 sample_D 0.14937319 0.02050879 0.02650570 0.08764727 0.7384572 0.3467337 0.4692873 0.1491655 0.9143110 0.09362514
  • Related