【问题标题】:Trouble extracting elements from a nested psych list using dplyr and purrr使用 dplyr 和 purrr 从嵌套的心理列表中提取元素时遇到问题
【发布时间】:2020-12-22 19:43:58
【问题描述】:

我在 R 中有一个嵌套数据框,我在其中应用了 psych 包中的一个函数。我将结果列表添加到数据框中。我现在想创建一个新列,其中包含该列表中的特定元素。原则上,我知道这是如何工作的,但由于某种原因,结果列表为 NULL。我可以验证我从中提取的列表不是空的,所以我想知道问题是什么。任何帮助将非常感激。下面的可重现示例。

library(psych)
library(tidyverse)

tibble( A = c( 1, 2, 3, 4),
        B = c( 1, 2, 3 ,4),
        C = c( 2, 3, 3, 5),
        group = c( 1, 1, 1, 1))%>%
      group_by( group) %>%
      nest() %>% 
      mutate( ICC_results = data %>% map( ICC)) -> df

# Now I would like to add a variable containing a numeric element from the list, so ideally use map_dbl, but that gives an error because extracting any element from the list results in an empty list

 df  %>%
       mutate( ICC3 = ICC_results %>% map( 9)) 

# A tibble: 1 x 4
# Groups:   group [1]
  group data             ICC_results ICC3  
  <dbl> <list>           <list>      <list>
1     1 <tibble [4 x 3]> <psych>     <NULL>

# I can verify that the element I am looking to extract is not empty
df %>%
  select( ICC_results) %>%
  unlist() %>%
  str()

List of 76
 $ ICC_results.results.type1       : chr "ICC1"
 $ ICC_results.results.type2       : chr "ICC2"
 $ ICC_results.results.type3       : chr "ICC3"
 $ ICC_results.results.type4       : chr "ICC1k"
 $ ICC_results.results.type5       : chr "ICC2k"
 $ ICC_results.results.type6       : chr "ICC3k"
 $ ICC_results.results.ICC1        : num 0.857
 $ ICC_results.results.ICC2        : num 0.862
 $ ICC_results.results.ICC3        : num 0.949
 $ ICC_results.results.ICC4        : num 0.947
 $ ICC_results.results.ICC5        : num 0.949
 $ ICC_results.results.ICC6        : num 0.982
 ....

【问题讨论】:

  • 你想从str(df$ICC_results)中提取哪个元素?
  • 第 9 个元素。我已经尝试过map(9)map("ICC_results.results.ICC3"),以及提取、采摘等所有变体......没有任何效果。
  • @Waldi:谢谢你的提示,我想我明白了。
  • 很好,类似于df$ICC_results[[1]]$results$ICC[[3]]?
  • 类似于@tmfmnk 建议的内容,但不那么漂亮。所以我放过世界,不要发布它:)

标签: r list dplyr purrr psych


【解决方案1】:

一个选项可能是:

df %>%
 group_by(group) %>%
 nest() %>% 
 mutate(ICC_results = map_dbl(data, 
                              ~ pluck(ICC(.), "results") %>% 
                               filter(type == "ICC3") %>%
                               pull(ICC)))

  group data             ICC_results
  <dbl> <list>                 <dbl>
1     1 <tibble [4 × 3]>       0.949

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2023-03-22
    • 2023-04-01
    • 2012-04-09
    相关资源
    最近更新 更多