Skip to content

Instantly share code, notes, and snippets.

@chenpanliao
Created February 7, 2023 06:17
Show Gist options
  • Save chenpanliao/ab4efad95d420e19287307faf307ac0e to your computer and use it in GitHub Desktop.
Save chenpanliao/ab4efad95d420e19287307faf307ac0e to your computer and use it in GitHub Desktop.
library(tidyverse)
set.seed(1234)
d <-
tibble(
Time = letters[1:5] %>% rep(3),
Species = LETTERS[1:3] %>% rep(each = 5),
LS_2 = rpois(15, 1),
LS_3 = rpois(15, 2),
LS_4 = rpois(15, 3)
)
print(d)
# A tibble: 15 × 5
# Time Species LS_2 LS_3 LS_4
# <chr> <chr> <int> <int> <int>
# 1 a A 0 3 3
# 2 b A 1 1 2
# 3 c A 1 1 2
# 4 d A 1 1 3
# 5 e A 2 1 1
# 6 a B 1 1 4
# 7 b B 0 1 2
# 8 c B 0 1 2
# 9 d B 1 0 8
# 10 e B 1 1 4
# 11 a C 1 3 3
# 12 b C 1 2 3
# 13 c C 0 4 2
# 14 d C 3 3 3
# 15 e C 0 0 2
d %>%
# melt/gather 成 long table
gather("method", "Y", -Time, -Species) %>%
# dcast/spread 成新的 wide table
spread(Species, Y)
# A tibble: 15 × 5
# Time method A B C
# <chr> <chr> <int> <int> <int>
# 1 a LS_2 0 1 1
# 2 a LS_3 3 1 3
# 3 a LS_4 3 4 3
# 4 b LS_2 1 0 1
# 5 b LS_3 1 1 2
# 6 b LS_4 2 2 3
# 7 c LS_2 1 0 0
# 8 c LS_3 1 1 4
# 9 c LS_4 2 2 2
# 10 d LS_2 1 1 3
# 11 d LS_3 1 0 3
# 12 d LS_4 3 8 3
# 13 e LS_2 2 1 0
# 14 e LS_3 1 1 0
# 15 e LS_4 1 4 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment