【问题标题】:R purrr extracting multiple items from a list and converting to a data frameR purrr 从列表中提取多个项目并转换为数据框
【发布时间】:2025-12-01 01:10:02
【问题描述】:

我目前正在 R 中学习 purrr。我有执行以下操作的代码

  • 使用 r 中的 pysch 包从问题列表中获取平均值、SD、范围等
  • 在单个数据框中返回这些统计信息,其中列表项作为列添加到表中。在其学校下面的情况下。

以下是我认为大约 90% 的示例。我想要做的就是将学校的名称作为一列添加到数据框中,以便之后能够绘制它们。任何人都可以帮忙吗?只要运行bind_rows() 命令,下面的方法就会丢失名称

library(lavaan)
library(tidyverse)

# function pulls the mean, sd, range, kurtosis and skew
get_stats <- function(x){

  row_names <- rownames(x)
  mydf_temp <- x %>% 
    dplyr::select(mean, sd, range, kurtosis, skew) %>% 
    mutate_if(is.numeric, round, digits=2) %>% 
    filter(complete.cases(.))

  mydf_temp
}

# Generate the data for the reproducible example
mydf <- HolzingerSwineford1939 %>% 
  select(school, starts_with("x")) %>% 
  psych::describeBy(., group=.$school, digits = 2) 


# Gets the summary statistics per school
stats_summ <- mydf %>% 
  map(get_stats) %>% 
  bind_rows()

【问题讨论】:

    标签: r purrr


    【解决方案1】:

    我们可以使用来自bind_rows.id 参数

    mydf %>%
         map(get_stats) %>%
         bind_rows(., .id = 'group')
    

    使用iris 数据集的可重现示例

    mydf <- iris %>%   
               psych::describeBy(., group=.$Species, digits = 2) 
    

    【讨论】:

    • 谢谢@akrun,这正是我想要的