我想編寫一個處理多種數據類型的函數。下面是一個有效的例子,但看起來很笨拙。有沒有一個標準(或更好)的方式來做到這一點?編寫函數來處理R/Splus中的多種數據類型?
(它的幾次都是這樣我錯過了Matlab的這裏的一切都是一種類型:>)
myfunc = function(x) {
# does some stuff to x and returns a value
# at some point the function will need to find out the number of elements
# at some point the function will need to access an element of x.
#
# args:
# x: a column of data taking on many possible types
# e.g., vector, matrix, data.frame, timeSeries, list
x.vec <- as.vector(as.matrix(as.data.frame(x)))
n <- length(x.vec)
ret <- x.vec[n/3] # this line only for concreteness
return(ret)
}
語言只有一種類型我發瘋;-)。班級是你的朋友,讓你處理好事情和靈活。如下所述使用R的OO功能。 S3方法非常輕巧,實際上增加了很少的額外工作。作爲交換,你會得到美妙的行爲,就像能夠對任何事情調用summary()一樣。 – 2011-03-31 23:52:44