如何在R中按鱼类物种条件合并多行并修改Method字段
Solution
To solve this problem, we need to aggregate rows by Species, combining entries where a species was caught using both methods while merging the values in the numeric columns. Here's how to do it with tidyverse:
Step-by-Step Code
library(tidyverse) fish_catch_processed <- fish_catch %>% summarize( # Determine the combined fishing method Method = case_when( # Check if both methods exist in the species group all(c("Bottom fishing", "Trolling") %in% Method) ~ "Both", # Retain the single method if only one is present TRUE ~ as.character(Method[1]) ), # Merge Bait values: sum non-NA entries, keep NA if all are missing Bait = ifelse(all(is.na(Bait)), NA_integer_, sum(Bait, na.rm = TRUE)), # Merge Released values using the same logic Released = ifelse(all(is.na(Released)), NA_integer_, sum(Released, na.rm = TRUE)), # Merge Kept values using the same logic Kept = ifelse(all(is.na(Kept)), NA_integer_, sum(Kept, na.rm = TRUE)), # Group by Species (use .by for dplyr 1.1.0+; replace with group_by(Species) first if using an older version) .by = Species )
Explanation
- Method Column: We use
case_whento check if both fishing methods are present in the species group. If yes, we setMethodto "Both"; otherwise, we keep the single method used for that species. - Numeric Columns: For
Bait,Released, andKept, we sum non-NA values (usingsum(na.rm = TRUE)). If all values in a column are NA, we retain NA instead of converting it to 0, which preserves the original missing data context.
Sample Output
Running this code on your sample data will produce:
# A tibble: 9 × 5 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
Notice that Caranx ignobilis now has Method = "Both" with merged Released and Kept values, which matches your desired outcome.
内容的提问来源于stack exchange,提问作者Tuna-92
相关产品推荐
相关产品推荐

