Reputation: 1137
I have an R summary of a vector:
summary(vector)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.000 1.000 2.000 6.699 6.000 559.000
and I would like to add a column with the standard deviation:
SomethingNew(vector)
Min. 1st Qu. Median Mean 3rd Qu. Max. Std.Dev.
1.000 1.000 2.000 6.699 6.000 559.000 17.02
The formula for the last column is
round(sd(vector),2)
but I have no clue as to how to add it to the summary data frame in the same display. Any help appreciated, cheers.
Upvotes: 3
Views: 6545
Reputation: 7592
Try writing a new function to do so. I have written a short overview of how to write simple functions (link) you can use as a resource.
Essentially, you want the following:
mySummary <- function(vector, na.rm = FALSE, round = 2){
results <- c(summary(vector), 'Std. Dev' = round(sd(vector, na.rm), 2))
return(results)
}
Upvotes: 4
Reputation: 61154
Try this
> set.seed(1)
> vector <- rnorm(100, 20, 5)
> c(summary(vector), sd=sd(vector))
Min. 1st Qu. Median Mean 3rd Qu. Max. sd
8.927000 17.530000 20.570000 20.540000 23.460000 32.010000 4.490997
rounding:
> round(c(summary(vector), sd=sd(vector)), 2)
Min. 1st Qu. Median Mean 3rd Qu. Max. sd
8.93 17.53 20.57 20.54 23.46 32.01 4.49
Upvotes: 2
Reputation: 81693
Here's one way to do it:
vec <- 1:10 # an example vector
summ <- summary(vec) # create the summary
summ["Std.Dev."] <- round(sd(vec),2) # add the new value
The result:
Min. 1st Qu. Median Mean 3rd Qu. Max. Std.Dev.
1.00 3.25 5.50 5.50 7.75 10.00 3.03
Upvotes: 9