我怎样才能在数字前放置字符?

时间:2014-05-29 10:06:32

标签: r

xx=matrix(,ncol=4,nrow=6)
x=iris[,1:4]   

i=1
while(i<=4){
  xx[1,i]=min(x[,i])
  xx[2,i]=quantile(x[,i])[2]
  xx[3,i]=median(x[,i])
  xx[4,i]=mean(x[,i])
  xx[5,i]=quantile(x[,i])[4]
  xx[6,i]=max(x[,i])
  i=i+1
  dimnames(xx)=list(c("Min", "1st Qu", "median","mean","3rd Qu","Max"), names(x))
  dimnames(xx)[[1]]=rep("",nrow(xx)) 
  options(digits=4) 
}
print(xx)

我想上传截图但我不能因为声誉而抱歉。感谢您的帮助,我可以制作上面的代码,但它有一点问题。我可以在数字前加字符吗?

现在值为5.1005.800,但我希望如下:1st Qu.:5.100Median :5.800

谢谢

2 个答案:

答案 0 :(得分:1)

这里有一种方法来重新编码&#34; ,summary功能。

我正在尝试使用xxapply个函数。有powfrul工具,是做事的标准方法。避免R中的循环,特别是它们的副作用。

## helper function
Quantile <- function(which,...)
  function(...)quantile(...)[which]
## init functions and columns 
funcs <- 
 c(min,Quantile(2),median,mean,Quantile(4),max)
names <- 
c("Min   ", "1st Qu", "Median","mean  ","3rd Qu","Max   ")
## a summary of o column
summary_vector <- 
function(x)
 mapply(function(n,f)paste(n,format(f(x),digits=2),sep=':'),
   names,funcs)
## apply it for all columns   
sapply(iris[,1:4],summary_vector)

这给出了这个输出:

       Sepal.Length Sepal.Width  Petal.Length Petal.Width 
Min    "Min   :4.3" "Min   :2"   "Min   :1"   "Min   :0.1"
1st Qu "1st Qu:5.1" "1st Qu:2.8" "1st Qu:1.6" "1st Qu:0.3"
Median "Median:5.8" "Median:3"   "Median:4.3" "Median:1.3"
mean   "mean  :5.8" "mean  :3.1" "mean  :3.8" "mean  :1.2"
3rd Qu "3rd Qu:6.4" "3rd Qu:3.3" "3rd Qu:5.1" "3rd Qu:1.8"
Max    "Max   :7.9" "Max   :4.4" "Max   :6.9" "Max   :2.5"

summary(iris[,1:4])比较:

 Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
 Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
 Median :5.800   Median :3.000   Median :4.350   Median :1.300  
 Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
 Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500

答案 1 :(得分:0)

以下是我从cgwtools::mystat打印类似输出到控制台的方法。 (numdig是定义要显示的精度的函数参数)

 allstats <- data.frame(cbind(min = min(x), max = max(x), 
        mean = mean(x), median = median(x), sdev = sd(x), skew = theskew(x), 
        kurtosis = thekurt(x)), row.names = "")
    if (printit) {
        print(format(allstats[1:4], digits = numdig))
        print(format(allstats[5:7], digits = numdig))
    }