Transponse or pivot


My dataframe is like the image above, how do i make it like the image below?
Thx u

Are you looking for something like the following code? Note that all of the data become characters because one of the original columns had characters and rotating the data causes every column to contain a character value.

DF <- data.frame(Taxo = c("T1","T2","T3","T4","T5"),
                 A = 1:5, 
                 B = c("V","W","X","Y","Z"),
                 C = 11:15,
                 D= 21:25,
                 E = 31:35)
DF
#>   Taxo A B  C  D  E
#> 1   T1 1 V 11 21 31
#> 2   T2 2 W 12 22 32
#> 3   T3 3 X 13 23 33
#> 4   T4 4 Y 14 24 34
#> 5   T5 5 Z 15 25 35
library(tidyverse)
DFnew <- DF |> mutate(across(everything(), as.character)) |> 
  pivot_longer(-Taxo) |> 
  pivot_wider(names_from = "Taxo", values_from = "value")

DFnew
#> # A tibble: 5 × 6
#>   name  T1    T2    T3    T4    T5   
#>   <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 A     1     2     3     4     5    
#> 2 B     V     W     X     Y     Z    
#> 3 C     11    12    13    14    15   
#> 4 D     21    22    23    24    25   
#> 5 E     31    32    33    34    35

Created on 2024-03-11 with reprex v2.0.2

1 Like

This topic was automatically closed 21 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.