r - 根据 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."
解决方案
在base R
中,一个选项是split
数据子集,即“id”中的“cont”为 TRUE 的地方list
。然后与inlist
一起循环,检查行是否超过 1 行,然后调用names
list
Map
if
unique
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."
推荐阅读
- java - 进程在 Linux 中通过与 putty 的 ssh 连接被杀死
- java - 方形网格上的原始方程是发散的(计算流体动力学)
- python - 循环遍历字符串python中的json数组
- amazon-cloudformation - 如何在 AWS codestar 中设置环境属性?
- c# - C# WPF - 自定义控件拖放(Visual Studio 风格)
- go - 通过导入父目录,使用 golang 导入子包?
- laravel - Laravel sortBy()无法对集合进行排序
- git - 使用 Git,让人们看到同一项目的不同版本的最佳方式是什么?
- c# - Linq 语句查询,可能的组
- javascript - Wordpress 中的滑块