John Smith
John Smith

Reputation: 2886

R purrr extracting multiple items from a list and converting to a data frame

I am currently learning purrr in R. I have code which does the following

Below is an example where I'm about 90% there i think. All i want to do is add the names of the schools to the dataframe as a column so as to be able to chart them afterwards. Can anyone help? The method below loses the names as soon as the bind_rows() command is run

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()

Upvotes: 1

Views: 437

Answers (1)

akrun
akrun

Reputation: 887901

We can use the .id argument from bind_rows

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

Using a reproducible example with iris dataset

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

Upvotes: 1

Related Questions