library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5 ✓ purrr 0.3.4
## ✓ tibble 3.1.4 ✓ dplyr 1.0.7
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 2.0.1 ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
Let’s say I want data of the following shape:
example <- tribble(
~gene, ~time0h, ~time1h, ~time3h, ~time4h,
"ASS", 4.12, 5.2, 3.4, 3.2,
"BAS", 1.2, 3.4, 4.6, 3.8,
"CAS", 10.2, 2.3, 0.8, 0.1
)
example
## # A tibble: 3 × 5
## gene time0h time1h time3h time4h
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 ASS 4.12 5.2 3.4 3.2
## 2 BAS 1.2 3.4 4.6 3.8
## 3 CAS 10.2 2.3 0.8 0.1
(Example from Mfuzz)
To start I have the following shape:
df <- tribble(
~time, ~ASS, ~BAS, ~CAS,
"time0h", 4.12, 1.2, 10.2,
"time1h", 5.2, 3.4, 2.3,
"time3h", 3.4, 4.6, 0.8,
"time4h", 3.2, 3.8, 0.1
)
df
## # A tibble: 4 × 4
## time ASS BAS CAS
## <chr> <dbl> <dbl> <dbl>
## 1 time0h 4.12 1.2 10.2
## 2 time1h 5.2 3.4 2.3
## 3 time3h 3.4 4.6 0.8
## 4 time4h 3.2 3.8 0.1
So I want to transpose the dataframe, since my rows are what I want my columns to be:
t(df)
## [,1] [,2] [,3] [,4]
## time "time0h" "time1h" "time3h" "time4h"
## ASS "4.12" "5.20" "3.40" "3.20"
## BAS "1.2" "3.4" "4.6" "3.8"
## CAS "10.2" " 2.3" " 0.8" " 0.1"
While the code is simple, it creates a character vector:
typeof(t(df))
## [1] "character"
And I have to do some manual clean up when converting back to a tibble as a result:
reshaped <- df %>%
select(!time) %>%
t() %>%
as_tibble(.name_repair = "minimal")
colnames(reshaped) <- df$time
reshaped$gene <- colnames(df)[2:ncol(df)]
reshaped <- reshaped %>%
relocate(gene)
reshaped
## # A tibble: 3 × 5
## gene time0h time1h time3h time4h
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 ASS 4.12 5.2 3.4 3.2
## 2 BAS 1.2 3.4 4.6 3.8
## 3 CAS 10.2 2.3 0.8 0.1
It feels like I should be able to do a transpose without getting the wonky intermediate character vector, but couldn’t find a simple solution with either pivot_*
from {tidyr}
.