Monday, December 3, 2012

How to create a matrix starting from variables in R


> c1 <- c(2.2, 6.123, 4.333, 5.34567)
> c2 <- c(5, 1.123456, 12.1123, 0.322)
> c3 <- c1/c2
> c4 <- c1*c2
> 
> x <- data.frame(c1, c2, c3, c4)
> row.names(x) <- c("r1", "r2", "r3", "r4")
> x
        c1        c2         c3        c4
r1 2.20000  5.000000  0.4400000 11.000000
r2 6.12300  1.123456  5.4501467  6.878921
r3 4.33300 12.112300  0.3577355 52.482596
r4 5.34567  0.322000 16.6014596  1.721306
> 
> fx <- format(x, digits=3)
> fx
     c1     c2     c3    c4
r1 2.20  5.000  0.440 11.00
r2 6.12  1.123  5.450  6.88
r3 4.33 12.112  0.358 52.48 
r4 5.35  0.322 16.601  1.72

To print the first column:

> fx[,1]
[1] "2.20" "6.12" "4.33" "5.35"

To print the second row:

> fx[2,]
     c1     c2     c3    c4
r2 6.12  1.123  5.450  6.88

No comments:

Post a Comment