若R将thoroghlly与S4遵守,以下就足够了:
setMethod("+",
signature(e1 = "character", e2 = "character"),
function (e1, e2) {
paste(e1, e2, sep = "")
})
但是,这给出了一个错误的方法((希望这会改变R的功能版本。)
你可以做的最好的是定义新的类“字符串”,其行为与“字符”类完全一样:
setClass("string", contains="character")
string <- function(obj) new("string", as.character(obj))
,并定义最常用的方法,其中R允许:
setMethod("+", signature(e1 = "character", e2 = "ANY"),
function (e1, e2) string(paste(e1, as.character(e2), sep = "")))
现在就来试试:
tt <- string(44444)
tt
#An object of class "string"
#[1] "44444"
tt + 3434
#[1] "444443434"
"sfds" + tt
#[1] "sfds44444"
tt + tt
#[1] "4444444444"
343 + tt
#Error in 343 + tt : non-numeric argument to binary operator
"sdfs" + tt + "dfsd"
#An object of class "string"
#[1] "sdfs44444dfsd"
可能重复:http://stackoverflow.com/questions/1319698/why-doesnt-operate-on-characters-in-r – 2011-01-19 12:19:57
HTTPS://stat.ethz。ch/pipermail/r-help/2005-February/066719.html – mdsumner 2011-05-31 14:33:54