我正在尝试为特定类编写rbind.character <- function(...) {
do.call("paste", list(...))
}
方法。这是一个简单的例子,它不起作用(至少对我而言):
> methods("rbind")
[1] rbind.character rbind.data.frame rbind.rootogram* rbind.zoo*
see '?methods' for accessing help and source code
输入此功能后,我似乎可以确认它是R知道的有效方法:
> rbind("abc", "xyz")
[,1]
[1,] "abc"
[2,] "xyz"
> #### compared with ####
> rbind.character("abc", "xyz")
[1] "abc xyz"
但是,如果我尝试使用它,则无法识别:
rbind("abc", "xyz")
帮助页面表示调度内部执行如下:
使用public String sendCommand(String cmd, CommPortIdentifier portX) throws UnsupportedCommOperationException, IOException, PortInUseException {
String result="kosong";
SerialPort port = null;
try {
port = (SerialPort) portX.open("Wavecom", 5000); // Wait max. 10 sec. to acquire port
} catch (PortInUseException e) {
System.err.println("Port already in use: " + e);
System.exit(0);
}
try {
port.setSerialPortParams(
115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
System.out.println(e.toString());
}
BufferedReader is = null;
PrintStream os = null;
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream");
is = null;
}
try {
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Can't open output stream");
is = null;
}
os.print(cmd);
os.print("\n\r");
String respon;
try {
Thread.sleep(1000);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
try {
while ((respon = is.readLine())!=null) {
result=is.readLine();
try {
Thread.sleep(1500);//asal 3000
} catch (InterruptedException ex) {
Logger.getLogger(ThreadConsloe.class.getName()).log(Level.SEVERE, null, ex);
}
if(result.contains("\n")){
// result.rep
}
System.out.println("result "+result);
}
} catch (IOException e)
{
System.err.println("Can't recieve input signals");
}
port.close();
return result;
}
,我相信所有这些标准都得到满足。什么给出了,我该如何解决?
答案 0 :(得分:9)
attributes("abc")
#NULL
character
向量没有class属性。我不认为rbind
可以为隐式类调度方法。
答案 1 :(得分:3)
解决方法是定义自己的类:
b <- "abc"
class(b) <- "mycharacter"
rbind.mycharacter <- function(...) {
do.call("paste", list(...))
}
rbind(b, b)
# [1] "abc abc"
罗兰在评论中很好地解释了它与character
不起作用的原因。
答案 2 :(得分:1)
rbind
不是标准的S3函数,因此您无法“拦截”character
。
幸运的是,您可以覆盖默认实现。试试:
rbind.character <- function(...) {
print("hello from rbind.character")
}
rbind <- function(...) {
args <- list(...)
if (all(vapply(args, is.character, logical(1)))) {
rbind.character(...)
} else {
base::rbind(...)
}
}
基本上,我们检查参数是否都是字符。如果是这样,我们称之为角色功能。如果没有,我们调用默认实现。