【问题标题】:Grouping and nesting data produces an error in R with tidyverse使用 tidyverse 在 R 中对数据进行分组和嵌套会产生错误
【发布时间】:2021-09-06 22:05:42
【问题描述】:

我正在尝试为一些动物追踪数据计算一些家庭范围估计值。为此,amt 包的作者recommend grouping by ID and then nesting

但是当我这样做时,我收到以下错误:

错误:groups 属性不是具有最后一列的数据框 叫.rows

这是一个重现错误的示例:

library(amt)
library(tidyverse)

    data(deer)
    mini_deer <- deer[1:100, ]
    nesttrk <- mini_deer %>% group_by(burst_) %>% 
      nest() 
    nesttrk

总体目标是获得每个 ID(或在本例中为 burst_)的归属范围大小估计值

mini_deer %>% group_by(burst_) %>%  nest(-burst_) %>%
  mutate(mcparea = map(data, ~ hr_mcp(., levels = c(0.95)) %>% hr_area)) %>%
  dplyr::select(burst_, mcparea) %>% unnest()

【问题讨论】:

    标签: r dataframe tidyverse


    【解决方案1】:

    我没有使用amt 包,但从使用nest 的错误消息来看,它似乎需要某种特定格式的数据,因为与数据框嵌套可以正常工作。 (mini_deer %&gt;% as.data.frame() %&gt;% group_by(burst_) %&gt;% nest()) 但我们在转换为数据帧时会丢失类。

    拆分和合并方法有效 -

    library(amt)
    library(tidyverse)
    
    mini_deer %>% 
      group_split(burst_, .keep = TRUE) %>%
      map_df(~ hr_mcp(., levels = c(0.95)) %>% hr_area) %>%
      mutate(burst_ = unique(mini_deer$burst_), .before = 1)
    
    #  burst_ level what         area
    #   <dbl> <dbl> <chr>       <dbl>
    #1      1  0.95 estimate  180927.
    #2      2  0.95 estimate 1886603.
    #3      3  0.95 estimate       0 
    #4      4  0.95 estimate       0 
    #5      5  0.95 estimate   14476.
    

    【讨论】:

      【解决方案2】:

      我们可以使用 nest_bymutate 本身,然后使用 unnest list

      library(amt)
      library(dplyr)
      library(tidyr)
      mini_deer %>% 
          nest_by(burst_) %>%
          transmute(mcparea = list(hr_mcp(data, levels = 0.95) %>% 
                        hr_area))  %>% 
          ungroup %>%
          unnest(mcparea)
      # A tibble: 5 x 4
        burst_ level what         area
         <dbl> <dbl> <chr>       <dbl>
      1      1  0.95 estimate  180927.
      2      2  0.95 estimate 1886603.
      3      3  0.95 estimate       0 
      4      4  0.95 estimate       0 
      5      5  0.95 estimate   14476.
      

      【讨论】:

        猜你喜欢
        • 2021-01-03
        • 2017-06-29
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        • 2020-06-11
        • 1970-01-01
        相关资源
        最近更新 更多