【问题标题】:Catching an error based on unique id values in a data.frame根据 data.frame 中的唯一 id 值捕获错误
【发布时间】:2021-08-05 02:54:51
【问题描述】:

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

这在 R 中可能吗?

在下面的玩具示例中,id == "B" 应该抛出一个错误,因为 pos 是变化的 (1,2,3),而 mp 的值 (即 1,3) 对应于 @987654329 的行@ 不一样。

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."

【问题讨论】:

    标签: r dataframe function error-handling


    【解决方案1】:

    base R 中,一种选择是将split 数据子集,即通过'id' 将'cont' 为TRUE 转换为list。然后在Map 中循环listlistnames,检查ifunique 行有超过1 行,然后调用stop

    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."
    

    【讨论】:

    • @rnorouzian 你能测试我更新的解决方案吗?还要检查lst1[["Brown"]]
    • @rnorouzian 请注意stop 将在第一次出现该问题时执行并抛出错误。它不会显示所有有问题的 id
    • 阿伦,this 可能会感兴趣。
    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多