讀到此 The art of R Programming 讀書報告。文中指:
Vector creation using “c(1,2,3,4)”. Vectors in R are similar to lists in Python, it would be more natural to add a little syntactic sugar and use “[1,2,3,4]” for vector creation i.e. the same syntax as Python and many other languages.
在 R ,建立 vector 是用 c() 。而建立 matrix ,也是要先用 c() 建立 vector ,再排成 matrix 。如
[code]
# < -
mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol=3, byrow=TRUE,
                    dimnames = list(c("row1", "row2"),
                                    c("C.1", "C.2", "C.3")))
[/code]
我沒有能力寫好勁的 syntactic sugar ,但是好廢的 quick-and-dirty 扮 syntactic sugar 也是可以的。
[code]
mm <- function(mj) {
  mj.sp <- unlist(strsplit(mj, ";"))
  for (i in 1:length(mj.sp)) {
    mj.row <- unlist(strsplit(mj.sp[i], " "))
    mj.row <- as.numeric(mj.row[mj.row!=""])
    mj.rowvec <- matrix(mj.row, byrow=TRUE, nrow=1)
    if (i == 1){
      output.mat <- mj.rowvec
    }
    else {
    output.mat <- rbind(output.mat, mj.rowvec)
  }
  }
  return(output.mat)
}
[/code]
用到的只是很簡單的 character functions ,參照 quick R 寫成的。
用法是:
[code]
somematrix <- mm("1 2 3; 2 3 4; 3 4 5; 4 5 6") #4x3 matrix
col.vector <- mm("1; 2; 3; 4; 5") # column vector / 5x1 matrix
row.vector <- mm("1 2 3 4 5") # row vector / 1x5 matrix
[/code]
當然是沒有 matlab / octave 的方便 (( Matlab 的寫法是 somematrix = [1 2 3; 2 3 4; 3 4 5; 4 5 6])) ,亦沒有甚麼 exception handling 。如果可以省略代表 string 的 "" 符號更好。