【问题标题】:Can I use a dplyr pipe instead of lapplying over lists in R?我可以使用 dplyr 管道而不是覆盖 R 中的列表吗?
【发布时间】:2022-07-07 00:11:09
【问题描述】:

我想知道我是否可以将 tidyverse 用于迄今为止在 R 中使用列表的任务。 我得到了每个地块的物种丰度矩阵,我想用 vegan 包中的 vegdist 计算差异指数。之后我想把它放在长格式中删除自动比较等。 举个简单的例子,它就像 dplyr 的魅力:

library(tidyverse)
library(vegan)
df <- data.frame(spec1=sample.int(50,10,replace=T),
             spec2=sample.int(75,10,replace=T),
             spec3=sample.int(10,10,replace=T),
             spec4=sample.int(40,10,replace=T),
             spec5=sample.int(50,10,replace=T),
             spec6=sample.int(5,10,replace=T))

 df%>%
  vegdist() %>%
  as.matrix() %>%
  as_tibble(rownames= "rownames") %>%
  pivot_longer(-rownames) %>%
  filter(rownames < name) 

现在我想做同样的事情,但是物种属于不同的类别,每个类别都必须获得自己的距离矩阵,并且只有在它可以放回单个长格式数据框或 tibble 之后。

cat <- data.frame(spec=c("spec1","spec2","spec3","spec4","spec5","spec6"),
                  group=c("a","b","c","b","a","c"))
df%>%
  pivot_longer(cols = everything(),values_to="abundance",names_to="spec")%>%
  left_join(cat, by="spec")

一开始很简单,但在我习惯按列 group 将数据拆分为列表的时候,我正在努力寻找解决方案。我尝试了 group_by + pivot_wider + vegdistgroup_split 的组合,但不幸的是无法想出一个可行的解决方案。有没有人有建议,或者我应该坚持这种情况的清单?

【问题讨论】:

    标签: r list dplyr data-manipulation


    【解决方案1】:

    我们可以split 'spec' by 'group' 到 list,循环 list 然后 select 基于来自 list 的元素的列并应用 vegdist

    library(vegan)
    library(purrr)
    library(dplyr)
    library(tidyr)
    out <- map_dfr(split(cat$spec, cat$group), 
       ~  df %>%
             select(all_of(.x)) %>% 
             vegdist() %>% 
             as.matrix %>% 
             as_tibble(rownames = "rownames") %>% 
            pivot_longer(-rownames) %>% 
            filter(rownames < name), .id = 'group')
    

    -输出

    > out
    # A tibble: 135 × 4
       group rownames name   value
       <chr> <chr>    <chr>  <dbl>
     1 a     1        2     0.268 
     2 a     1        3     0.35  
     3 a     1        4     0.208 
     4 a     1        5     0.0682
     5 a     1        6     0.328 
     6 a     1        7     0.196 
     7 a     1        8     0.189 
     8 a     1        9     0.178 
     9 a     1        10    0.178 
    10 a     2        3     0.0822
    # … with 125 more rows
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2011-02-09
      • 2012-02-19
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多