Krug
Krug

Reputation: 1013

Rename one specific row of a matrix (R)

I could not find the answer to this very basic question. I want to rename one specific row of a matrix only. Easy to do with dataframes, how can it be done with a matrix? Sure, could convert back and forth, not the point.

This came to surface while trying to put together the output of functions quantile and mean into one matrix.

DF <- structure(list(FwdD1 = c(2.2, 2.8, 0.7, 1.1, -0.9, 2.5), FwdD2 = c(2.6,2.2, 2, -1.4, 2.8, 4), FwdD3 = c(1.2, 1.7, 9, -1.6, 1.7, 1.1),FwdD4 = c(1.6, 1.9, 5.4, 1.2, 1.4, 0.8), FwdD5 = c(4.7, 3,4.8, -1.2, 0, 0.2)), .Names = c("FwdD1", "FwdD2", "FwdD3","FwdD4", "FwdD5"), row.names = c("10007", "57926", "95462", "142373","181339", "229476"), class = "data.frame")

Quantiles <- round(apply(DF, 2, quantile, na.rm=TRUE),2)
Mean <- round(apply(DF, 2, mean, na.rm=TRUE),2)
Mean <- as.matrix(Mean,drop=FALSE)
QuantilesMean <- rbind(Quantiles,t(Mean))
rownames(QuantilesMean) <- c("0%","25%","50%","75%","100%","Mean")


#Output of QuantilesMean matrix:
     FwdD1 FwdD2 FwdD3 FwdD4 FwdD5
0%   -0.90 -1.40 -1.60  0.80 -1.20
25%   0.80  2.05  1.12  1.25  0.05
50%   1.65  2.40  1.45  1.50  1.60
75%   2.42  2.75  1.70  1.82  4.28
100%  2.80  4.00  9.00  5.40  4.80
Mean  1.40  2.03  2.18  2.05  1.92

Works fine, but if I were to have hundreds of rows it would not be practical. Thank you.

Upvotes: 3

Views: 9187

Answers (2)

Frank
Frank

Reputation: 66819

(For the question in the title, see @AdamQuek's answer.)

For your particular application, try:

res = sapply(DF, function(x) c(quantile(x), Mean = mean(x)))

If you need to round when browsing it:

round(res, 2)

     FwdD1 FwdD2 FwdD3 FwdD4 FwdD5
0%   -0.90 -1.40 -1.60  0.80 -1.20
25%   0.80  2.05  1.12  1.25  0.05
50%   1.65  2.40  1.45  1.50  1.60
75%   2.42  2.75  1.70  1.82  4.28
100%  2.80  4.00  9.00  5.40  4.80
Mean  1.40  2.03  2.18  2.05  1.92

Upvotes: 5

Adam Quek
Adam Quek

Reputation: 7153

Straightforward method through indexing.

rownames(QuantilesMean)[6]<-"Mean"

Upvotes: 9

Related Questions