【问题标题】:Combine summary and nrow结合总结和nrow
【发布时间】:2015-05-30 17:02:37
【问题描述】:

我正在尝试创建一个可以查找摘要和行数的函数,所以首先我尝试创建如下内容:

G <- summary(mtcars)
H <- nrow(mtcars)
I <- ("# of Rows")
J <- (c(I,H))
K <- print(G,J)
K

我收到以下错误:

Error in format.default(unclass(x), digits = digits, justify = justify) : 

invalid 'digits' argument
In addition: Warning message:
In format.default(unclass(x), digits = digits, justify = justify) :
 NAs introduced by coercion
> K
Error: object 'K' not found

我想得到的是这样的:

         V1         
 Min.     :  19.35  
 1st Qu.  :  61.22  
 Median   : 126.76  
 Mean     : 212.96  
 3rd Qu.  : 158.13  
 Max.     : 1500.00  
 # of Rows: 367

显然我已经离开这里,但我似乎无法让我的矩阵和向量一起工作。任何帮助表示赞赏!

【问题讨论】:

  • 如果没有可重现的示例,您的问题实际上并不清楚。您是否希望该函数仅适用于一列 data.frames?
  • 抱歉,添加示例。之前以为很清楚,显然是错的。谢谢

标签: r function matrix vector summary


【解决方案1】:

大概是这样的:

> print(rbind(summary(mtcars), paste0("Rows.  :", nrow(mtcars))), quote = FALSE)
      mpg             cyl             disp             hp             drat             wt       
 Min.   :10.40   Min.   :4.000   Min.   : 71.1   Min.   : 52.0   Min.   :2.760   Min.   :1.513  
 1st Qu.:15.43   1st Qu.:4.000   1st Qu.:120.8   1st Qu.: 96.5   1st Qu.:3.080   1st Qu.:2.581  
 Median :19.20   Median :6.000   Median :196.3   Median :123.0   Median :3.695   Median :3.325  
 Mean   :20.09   Mean   :6.188   Mean   :230.7   Mean   :146.7   Mean   :3.597   Mean   :3.217  
 3rd Qu.:22.80   3rd Qu.:8.000   3rd Qu.:326.0   3rd Qu.:180.0   3rd Qu.:3.920   3rd Qu.:3.610  
 Max.   :33.90   Max.   :8.000   Max.   :472.0   Max.   :335.0   Max.   :4.930   Max.   :5.424  
 Rows.  :32      Rows.  :32      Rows.  :32      Rows.  :32      Rows.  :32      Rows.  :32     
      qsec             vs               am              gear            carb      
 Min.   :14.50   Min.   :0.0000   Min.   :0.0000   Min.   :3.000   Min.   :1.000  
 1st Qu.:16.89   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:3.000   1st Qu.:2.000  
 Median :17.71   Median :0.0000   Median :0.0000   Median :4.000   Median :2.000  
 Mean   :17.85   Mean   :0.4375   Mean   :0.4062   Mean   :3.688   Mean   :2.812  
 3rd Qu.:18.90   3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:4.000   3rd Qu.:4.000  
 Max.   :22.90   Max.   :1.0000   Max.   :1.0000   Max.   :5.000   Max.   :8.000  
 Rows.  :32      Rows.  :32       Rows.  :32       Rows.  :32      Rows.  :32   

鉴于 data.frame 中每个向量中的观察数量(根据定义)是恒定的,我不太确定为什么为每个变量设置该数量是有用的,但确实如此。

【讨论】:

  • 感谢您的解决方案。我应该指定我的数据只有一个向量。现在我可以去弄清楚 rbind 和 quote 的作用(即学会钓鱼)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 2019-01-14
  • 2021-04-06
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多