Как условно объединить две строки с несколькими значениями вместе и мутировать в R? - PullRequest
2 голосов
/ 29 апреля 2020

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)))

Ответы [ 2 ]

2 голосов
/ 29 апреля 2020

Вот один подход, использующий tidyverse. Вы можете group_by(Species) и установить Method в значение «Оба», если в этот вид включены как Нижняя рыбалка, так и Троллинг. Затем вы можете group_by указать и Вид, и метод и использовать fill для замены NA известными значениями. В конце используйте slice, чтобы оставить по одной строке для каждого вида / метода. Предполагается, что в противном случае у вас будет по 1 строке для каждого вида / метода - пожалуйста, дайте мне знать, если это не так.

library(tidyverse)

fish_catch %>%
  group_by(Species) %>%
  mutate(Method = ifelse(all(c("Bottom fishing", "Trolling") %in% Method), "Both", as.character(Method))) %>%
  group_by(Species, Method) %>%
  fill(c(Bait, Released, Kept), .direction = "updown") %>%
  slice(1)

Вывод

# A tibble: 9 x 5
# Groups:   Species, Method [9]
  Species                  Method          Bait Released  Kept
  <chr>                    <chr>          <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         Both              NA        1     1
5 Epinephelus fasciatus    Bottom fishing    NA        3    NA
6 Epinephelus multinotatus Bottom fishing    NA       NA     5
7 Other species            Bottom fishing    NA        1    NA
8 Thunnus albacares        Trolling          NA       NA     1
9 Variola louti            Bottom fishing    NA       NA     1
0 голосов
/ 29 апреля 2020

Это должно помочь вам начать. Вы можете добавить другие столбцы к функции суммирования.

library(tidyverse)    
fish_catch %>% select(-Bait, -Released, -Kept) %>%
  group_by(Species) %>%
  summarize(Method = paste0(Method, collapse = "")) %>%
  mutate(Method = fct_recode(Method, "both" = "TrollingBottom fishing"))

# A tibble: 9 x 2
  Species                  Method        
  <chr>                    <fct>         
1 Aethaloperca rogaa       Bottom fishing
2 Aprion virescens         Bottom fishing
3 Balistidae spp.          Bottom fishing
4 Caranx ignobilis         both          
5 Epinephelus fasciatus    Bottom fishing
6 Epinephelus multinotatus Bottom fishing
7 Other species            Bottom fishing
8 Thunnus albacares        Trolling      
9 Variola louti            Bottom fishing
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...