为什么pivot_longer() 在其输出中仅嵌套四个整数值

Rez*_*eza 3 loops r dataframe tidyr tidyverse

我想知道为什么pivot_longer()下面的调用会返回列下的嵌套输出value

foo <- function(){ 
 n_subj = 5
 n_trials = 20
 subj_intercepts = rnorm(n_subj, 0, 1)
 slope = .6
 mx = 30
 data = data.frame(subject = rep(1:n_subj, each=n_trials),
                   intercept = rep(subj_intercepts, each=n_trials)) %>%
   mutate(x = rnorm(n(), mx, 1),
          y = intercept + slope*(x-mean(x)) + rnorm(n(), 0, 1))
 
mlm = coef(summary(lmer(y ~ x + (1|subject), data=data)))[2,1]
ols = coef(summary(lm(y ~ x, data=data)))[2,1]
list(ols=ols, mlm=mlm)
}
 
kk <- data.frame(t(replicate(2, foo())))

pivot_longer(kk, everything())

#  name  value    
#  <chr> <list>   
#1 ols   <dbl [1]>
#2 mlm   <dbl [1]>
#3 ols   <dbl [1]>
#4 mlm   <dbl [1]>
Run Code Online (Sandbox Code Playgroud)

Tar*_*Jae 5

您正在函数中创建一个列表:unlist在函数代码末尾添加/换行以获得tibble

foo <- function(){ 
    n_subj = 5
    n_trials = 20
    subj_intercepts = rnorm(n_subj, 0, 1)
    slope = .6
    mx = 30
    data = data.frame(subject = rep(1:n_subj, each=n_trials),
                      intercept = rep(subj_intercepts, each=n_trials)) %>%
        mutate(x = rnorm(n(), mx, 1),
               y = intercept + slope*(x-mean(x)) + rnorm(n(), 0, 1))
    
    mlm = coef(summary(lmer(y ~ x + (1|subject), data=data)))[2,1]
    ols = coef(summary(lm(y ~ x, data=data)))[2,1]
    unlist(list(ols=ols, mlm=mlm))
}
Run Code Online (Sandbox Code Playgroud)

输出

  name  value
  <chr> <dbl>
1 ols   0.600
2 mlm   0.581
3 ols   0.441
4 mlm   0.528
Run Code Online (Sandbox Code Playgroud)