【问题标题】:Assigning new label / group by partial string matching with vector of shortened labels通过与缩短标签向量匹配的部分字符串分配新标签/组
【发布时间】:2021-11-13 13:30:00
【问题描述】:

我正在尝试在 R 中将数据分组在一起。我正在使用来自整洁的星期二挑战(全球海鲜、库存)的数据,并且希望将数据分组到海洋中。目前,数据分为海洋部分(例如东中大西洋和中东北大西洋)

   Ocean                      code   year    bio_sus    bio_nonsus
 1 Eastern Central Atlantic   NA     2015    57.1       42.9
 2 Eastern Central Atlantic   NA     2017    57.1       42.9
 3 Southeast Central Atlantic NA     2015    67.6       32.4
 4 Southeast Central Atlantic NA     2017    67.6       32.4

有没有办法将不同的海洋数据(bio_sus 和 bio_nonsus)组合成一个更大的数据位(例如,2015、2017 年大西洋的所有部分都合并成一个大西洋)。

我总共有四个不同的海洋:太平洋、大西洋、印度和地中海,它们是这样分割的

#This is the data: 

stock <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-10-12/fish-stocks-within-sustainable-levels.csv')

【问题讨论】:

标签: r data-wrangling


【解决方案1】:

这本质上是一个“多个部分字符串匹配”的问题。这里有一种方法。循环遍历部分字符串以获取每个部分匹配的索引,然后用匹配替换原始向量。然后根据你的新专栏进行总结。

library(dplyr)

stock <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-10-12/fish-stocks-within-sustainable-levels.csv')

oceans <- c("pacific", "atlantic", "indian", "mediterranean")
  
lu <- stack(sapply(oceans, grep, x = stock$Entity, ignore.case = TRUE))

stock$oceans <-  stock$Entity
stock$oceans[lu$values] <- as.character(lu$ind)

stock %>%
  group_by(oceans) %>%
  summarise(across(matches("^share"), sum))
#> # A tibble: 5 × 3
#>   oceans        `Share of fish stocks within biologi… `Share of fish stocks tha…
#>   <chr>                                         <dbl>                      <dbl>
#> 1 atlantic                                      742.                        458.
#> 2 indian                                        277.                        123.
#> 3 mediterranean                                  75.3                       125.
#> 4 pacific                                       894.                        306.
#> 5 World                                        1609.                        491.

reprex package (v2.0.1) 于 2021 年 11 月 13 日创建

【讨论】:

    【解决方案2】:

    为什么不使用 stringr 包的str_split() 来提取海洋,并为海洋创建一个列,为子段创建一个列?

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多