如何优化psych包describeBy()函数输出:仅保留Feuchte相关统计结果并生成结构化DataFrame
describeBy() Output to Keep Only Feuchte Rows & Add ID Column Let's fix your messy output step by step—your current code generates stats for all columns (Soll, Transtyp, Feuchte) which is why things look unorganized. Here's a streamlined approach to get exactly what you need:
Step 1: Load Required Packages
First, make sure you have these packages installed and loaded:
library(tidyverse) library(psych)
Step 2: Generate Targeted Descriptive Stats
Instead of running describeBy() on the entire data frame, focus only on the Feuchte column while grouping by Soll and Transtyp. Using mat = TRUE returns a structured matrix (instead of a messy list) which simplifies cleaning:
# Ungroup data, keep only relevant columns, then run describeBy desc_output <- df %>% ungroup() %>% select(Soll, Transtyp, Feuchte) %>% describeBy(group = list(.$Soll, .$Transtyp), mat = TRUE)
Step 3: Clean and Reshape the Output
Now convert the matrix to a tidy DataFrame, extract the Soll ID from row names, and filter out unwanted rows:
clean_data <- desc_output %>% as.data.frame() %>% # Move row names into a dedicated column rownames_to_column(var = "group_details") %>% # Split group details into Soll, Transtyp, and variable name separate(group_details, into = c("Soll", "Transtyp", "variable"), sep = "\\.") %>% # Keep only rows for Feuchte filter(variable == "Feuchte") %>% # Reorder columns to put Soll ID first, drop redundant variable column select(Soll, Transtyp, everything(), -variable) %>% # Optional: Convert Soll to numeric if needed mutate(Soll = as.numeric(Soll))
Step 4: Use or Export the Clean Data
Your tidy DataFrame is now ready for display or export:
# Show a pretty interactive table rmarkdown::paged_table(clean_data) # Export to CSV write.csv(clean_data, "feuchte_summary.csv", row.names = FALSE)
Why Your Original Code Caused Issues
Your initial code ran describeBy() on all columns (after removing Datum), which generated stats for Soll, Transtyp, and Feuchte—hence the messy rows like xxxx.Soll and xxxx.Transtyp. By targeting only Feuchte and using mat = TRUE, we eliminate those extra rows entirely, and tidyverse tools make it easy to split your Soll ID into its own dedicated column.
内容的提问来源于stack exchange,提问作者Effigy

