Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

r markdown - Creating tables with descriptive statistics in R

I would like some help on creating formatted tables in R - whether it's just using the normal IDE or R Markdown. There are two main things that I'd like to do:

  • Present the descriptive statistics (Mean, Median, Min, Max) by group based on different columns
  • Present the descriptive statistic based on the total sample (ungrouped data)

Sample data:

   df <- data.frame(Gender = c("F", "M", "F", "M", "M", "M", "M", "F", "M", "M"),
                 Young = c("Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y", "N"),
                 Age = c("14", "25", "13", "24", "14", "25", "13", "24", "10", "26"),
                 Location = c("Suburb", "Rural", "Suburb", "Rural","Suburb", "Rural","Suburb", "Rural","Suburb", "Rural"))

Expected results

Variable Mean Median Max Min
Gender
Female
Male
Location
Suburb
Rural
TOTAL
question from:https://stackoverflow.com/questions/65660743/creating-tables-with-descriptive-statistics-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get all the information that you need by getting the data in long format.

library(dplyr)
library(tidyr)

df <- type.convert(df, as.is = TRUE)

df %>%
  pivot_longer(cols = -Age) %>%
  group_by(name, value) %>%
  summarise(min_age = min(Age), 
            max_age = max(Age), 
            median_age = median(Age), 
            mean_age = mean(Age))

#  name     value  min_age max_age median_age mean_age
#  <chr>    <chr>    <int>   <int>      <int>    <dbl>
#1 Gender   F           13      24         14     17  
#2 Gender   M           10      26         24     19.6
#3 Location Rural       24      26         25     24.8
#4 Location Suburb      10      14         13     12.8
#5 Young    N           24      26         25     24.8
#6 Young    Y           10      14         13     12.8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...