R将汇总结果(所有数据帧列的统计信息)转换为数据帧

标签 r statistics summary describe

[我是 R 新手...]我有这个 dataframe :

df1 <- data.frame(c(2,1,2), c(1,2,3,4,5,6), seq(141,170)) #create data.frame
names(df1) <- c('gender', 'age', 'height') #column names

我希望将 df1 的摘要保存在如下所示的数据框对象中:

         count     mean    std      min      25%      50%      75%      max
age    30.0000   3.5000 1.7370   1.0000   2.0000   3.5000   5.0000   6.0000
gender 30.0000   1.6667 0.4795   1.0000   1.0000   2.0000   2.0000   2.0000
height 30.0000 155.5000 8.8034 141.0000 148.2500 155.5000 162.7500 170.0000

我已经在 Python 中使用 df1.describe().T 生成了这个。我怎样才能在 R 中做到这一点?

如果我的摘要数据框包含“dtype”、“null”(NULL 值的数量)、“unique”和“range”值(数量),这将是免费的进行全面的汇总统计:

         count     mean    std      min      25%      50%      75%      max  null  unique  range  dtype
age    30.0000   3.5000 1.7370   1.0000   2.0000   3.5000   5.0000   6.0000     0       6      5  int64
gender 30.0000   1.6667 0.4795   1.0000   1.0000   2.0000   2.0000   2.0000     0       2      1  int64
height 30.0000 155.5000 8.8034 141.0000 148.2500 155.5000 162.7500 170.0000     0      30     29  int64

上述结果的Python代码为:

df1.describe().T.join(pd.DataFrame(df1.isnull().sum(), columns=['null']))\
    .join(pd.DataFrame.from_dict({i:df1[i].nunique() for i in df1.columns}, orient='index')\
    .rename(columns={0:'unique'}))\
    .join(pd.DataFrame.from_dict({i:(df1[i].max() - df1[i].min()) for i in df1.columns}, orient='index')\
    .rename(columns={0:'range'}))\
    .join(pd.DataFrame(df1.dtypes, columns=['dtype']))

谢谢!

最佳答案

您可以使用这些库非常轻松且可读地完成此操作 - tidyrdplyr

library("tidyr")
library("dplyr")


df1 <- data.frame(c(2,1,2), c(1,2,3,4,5,6), seq(141,170)) #create data.frame
names(df1) <- c('gender', 'age', 'height') #column names
df2<- gather(df1,"attributes","value")

df2 %>% group_by(attributes) %>% summarise(count = n(), mean = mean(value), med = median(value),sd = sd(value), min = min(value), max = max(value))

#  A tibble: 3 x 7
#   attributes count       mean   med        sd   min   max
#         <chr> <int>      <dbl> <dbl>     <dbl> <dbl> <dbl>
# 1        age    30   3.500000   3.5 1.7370208     1     6
# 2     gender    30   1.666667   2.0 0.4794633     1     2
# 3     height    30 155.500000 155.5 8.8034084   141   170

关于R将汇总结果(所有数据帧列的统计信息)转换为数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38892219/

相关文章:

r - 使用 R 中的 ggplot2 按数据点数量对(或 alpha)箱线图进行着色

r - 使用重叠阈值逐行选择跨列的组合

R:如何计算 1,5*IQR 晶须的值

R 函数等效于 SAS 中的 proc 摘要

r - 使用 R 时 getPortfolio 中未使用的参数

r - 如何在 R markdown 中向 fig.cap 添加 LaTeX 符号?

android - 跟踪 Android 市场统计数据

r - 在geom_boxplot中更改晶须定义

r - R 中系数的不同 NA 操作和线性模型总结

python - 如何整合 MS Teams 的出席名单?