Reputation: 7
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)
I want to upload screenshots but i can't because of reputation sorry. Thanks to your help, I can make above code, but it has a little problem. Can I put characters in front of numbers?
Now values are 5.100
, 5.800
, but I want to make it like: 1st Qu.:5.100
, Median :5.800
Thank you
Upvotes: 0
Views: 72
Reputation: 21502
Here's how I print similar output to the console, from cgwtools::mystat
. (numdig
is a function argument defining the precision to display)
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))
}
Upvotes: 0
Reputation: 121578
Here one way to "recode" , summary
function.
I am trying to use xxapply
functions. There are powfrul tools and are the standard way to do things. Avoid loop in R , specially for their side effect.
## 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)
Which gives this output :
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"
Comparing to 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
Upvotes: 1