繁体   English   中英

在R中创建一条错误消息,用于标识不匹配的值

[英]Create an error message in R that also identifies non-matching values

我正在编写一个相当长的函数,它要求所有的名字(abun)都存在于rownames(x)中,但反之则不然。 如果不满足要求,我设计了它,以便函数抛出错误消息。 除了错误消息,我还想告诉用户哪些colnames(abun)不在rownames(x)中。 有任何想法吗? 我当前的停止和错误消息如下所示:

abun <- matrix(c(0.4,0,0.6,0.1,0.4,0.5), 
    nrow = 2, ncol = 3, byrow = TRUE, dimnames = list(c("x", "y"), 
    c("A","B","E")))

abun
    A   B   E
x 0.4 0.0 0.6
y 0.1 0.4 0.5

x<-data.frame("Trait1" =c(1,1,0,1),
                    "Trait2"=c(1,1,1,1),
                    "Trait3" =c(1,1,0,1),
                    "Trait4" =c(1,0,1,1))
rownames(x)<-c("A","B","C","D") 

x
  Trait1 Trait2 Trait3 Trait4
A      1      1      1      1
B      1      1      1      0
C      0      1      0      1
D      1      1      1      1               



if(any(colnames(abun) %in% rownames(x) != TRUE))
stop("The following species names in abun are missing trait information")

回到你之前的问题

colnames(abun)[
    !colnames(abun) %in% rownames(x)
    ]

这应该返回您需要的值。

像这样的东西?

if(any(colnames(abun) %in% rownames(x) != TRUE))
stop("The following species names in abun are missing trait information:",
     paste(setdiff(colnames(abun), rownames(x)), collapse=" "))

感谢@Hadley建议setdiff!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM