簡體   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