首页 > 解决方案 > 根据 data.frame 中的唯一 id 值捕获错误

问题描述

我想在stop()下面为我的 data.frame 创建一个,这样对于每个唯一的id,如果pos是变化的(例如,由 1s、2s 等组成),那么,如果mp行的值cont==TRUE不相同,我们应该抛出一个错误。

这在R中可能吗?

在下面的玩具示例中,id == "B"应该抛出一个错误,因为pos它是不同的 (1,2,3),并且mp行的值(即 1,3)cont==TRUE不同。

dat <- data.frame(id = rep(c("A","B"),2:3), mp = c(1,5, 2,1,3), cont = c(F,T, F,T,T), pos = c(1,1, 1:3))
#  id mp  cont pos
#1  A  1 FALSE   1
#2  A  5  TRUE   1
#3  B  2 FALSE   1
#4  B  1  TRUE   2
#5  B  3  TRUE   3

# Desired stop() message:
"Error: 'B' has a wrong value."

标签: rdataframefunctionerror-handling

解决方案


base R中,一个选项是split数据子集,即“id”中的“cont”为 TRUE 的地方list。然后与inlist一起循环,检查行是否超过 1 行,然后调用nameslistMapifuniquestop

lst1 <- split(dat[dat$cont,c("mp", "pos")], dat$id[dat$cont])
Map(function(x, y) if(nrow(unique(x)) > 1)  
     stop(sprintf("'%s' has a wrong value.", y), call. = FALSE), 
        lst1, names(lst1))
#Error: 'B' has a wrong value.

使用更新的示例

lst1 <- split(dat[dat$control, c("mpre", "post")], dat$study.name[dat$control])
Map(function(x, y) if(all(lengths(lapply(x, unique))  > 1))  
      stop(dQuote(sprintf("'%s' has a wrong value.", y), FALSE), call. = FALSE), 
         lst1, names(lst1))
#Error: "'Brown' has a wrong value."

推荐阅读