You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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_when to check if both fishing methods are present in the species group. If yes, we set Method to "Both"; otherwise, we keep the single method used for that species.
  • Numeric Columns: For Bait, Released, and Kept, we sum non-NA values (using sum(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:02:37