问题描述
我在R中有一个嵌套的数据框,我将psych软件包中的函数应用于该数据框。我将结果列表添加到数据框。我现在想创建一个新列,其中包含该列表中的特定元素。原则上,我知道这是如何工作的,但是由于某种原因,结果列表为NULL。我可以验证从中提取的列表不是空的,所以我想知道问题出在哪里。任何帮助将非常感激。下面是可复制的示例。
library(psych)
library(tidyverse)
tibble( A = c( 1,2,3,4),B = c( 1,C = c( 2,5),group = c( 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
....
解决方法
一个选项可能是:
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