Fi sh были пойманы с использованием различных методов ловли.
Я хотел бы объединить строки на основе Species
(это если они одного и того же вида fi sh), если они перехвачены обоими методами Bottom fishing
и Trolling
, это приведет к двум строки сворачиваются в одну строку, изменяя значение Method
на Both
.
Например, Caranx ignobilis
будет иметь новое Method
значение Both
. Столбцы Bait
Released
и Kept
также должны иметь значения в одной строке.
Species Method Bait Released Kept
4 Caranx ignobilis Both NA 1 1
Кажется, все так просто, но я часами чесал голову и игрался с case_when
как часть пакета tidyverse
.
Тиббл является результатом предварительно поднабора данных с использованием group_by
и pivot_wider
.
Вот как выглядит образец:
# A tibble: 10 x 5
# Groups: Species [9]
Species Method Bait Released Kept
<chr> <fct> <int> <int> <int>
1 Aethaloperca rogaa Bottom fishing NA NA 2
2 Aprion virescens Bottom fishing NA NA 1
3 Balistidae spp. Bottom fishing NA NA 1
4 Caranx ignobilis Trolling NA NA 1
5 Caranx ignobilis Bottom fishing NA 1 NA
6 Epinephelus fasciatus Bottom fishing NA 3 NA
7 Epinephelus multinotatus Bottom fishing NA NA 5
8 Other species Bottom fishing NA 1 NA
9 Thunnus albacares Trolling NA NA 1
10 Variola louti Bottom fishing NA NA 1
Данные:
fish_catch <- structure(list(Species = c("Aethaloperca rogaa", "Aprion virescens","Balistidae spp.", "Caranx ignobilis", "Caranx ignobilis", "Epinephelus fasciatus","Epinephelus multinotatus", "Other species", "Thunnus albacares","Variola louti"),
Method = structure(c(1L, 1L, 1L, 2L, 1L, 1L,1L, 1L, 2L, 1L), .Label = c("Bottom fishing", "Trolling"), class = "factor"),Bait = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,NA_integer_),
Released = c(NA, NA, NA, NA, 1L, 3L, NA, 1L,NA, NA),
Kept = c(2L, 1L, 1L, 1L, NA, NA, 5L, NA, 1L, 1L)), class = c("grouped_df","tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), groups = structure(list(Species = c("Aethaloperca rogaa", "Aprion virescens",
"Balistidae spp.","Caranx ignobilis", "Epinephelus fasciatus", "Epinephelus multinotatus","Other species", "Thunnus albacares", "Variola louti"), .rows = list(1L, 2L, 3L, 4:5, 6L, 7L, 8L, 9L, 10L)), row.names = c(NA,-9L), class = c("tbl_df", "tbl", "data.frame"), .drop = FALSE))
Маршрут, по которому я шел, но потом понял, что он не включает Species
или другие столбцы
mutate(Method = case_when(Method == "Bottom fishing" & Method == "Trolling" ~ "Both",
Method == "Bottom fishing" ~ "Bottom fishing",
Method == "Trolling" ~ "Trolling", TRUE ~ as.character(MethodCaught)))