我正在尝试在 R 中创建关于数据验证的报告;我已经使用 validate 包生成了数据的一般摘要,但我需要了解验证检查失败的细节。
我想要结束的是一个包含 id 的数据框、未通过测试的列以及未通过测试的值。但是,并非所有列都是强制性的,因此我需要能够在不知道该列是否存在的情况下检查数据是否通过。
对于其他带有强制数据的数据框,无论是否通过测试,我都将其转换为 True/False。例如:
library(dplyr)
library(validate)
library(tidyr)
test_df = data.frame(id = 1:10,
a = 11:20,
b = c(21:25,36,27:30),
c = c(41,52,43:50))
text_check = test_df %>% transmute(
a = a>21,
b = b > 31,
c = c> 51
)
value_fails<-data.frame(id = test_df$id, text_check[,-1][colSums(text_check[,-1]) > 0])
value_failures_gath = gather(value_fails, column, changed, -id) %>% filter(changed == TRUE)
value_failures_gath$Value = apply(value_failures_gath, c(1), function(x)
test_df[test_df$id == x[['id']], grep(x[['column']], colnames(test_df))])
value_failures_gath<-value_failures_gath %>% arrange(id, column)
value_failures_gath$changed<-NULL
colnames(value_failures_gath)<-c('ID','Field','Value')
> value_failures_gath
ID Field Value
1 2 c 52
2 6 b 36
我有一个带有我想要创建的检查的数据框,样式如下:
second_data_check = data.frame(a = 'a>21',
b = 'b > 31',
c = 'c> 51',
d = 'd> 61')
我不能按原样运行这些,因为我们没有要检查的 D 列,但是通过此验证运行的其他数据框可能有 D 列但没有 B 列。我可以过滤此数据框以仅包含我们拥有的列的测试,但是有没有办法将此数据框中的测试应用为检查?有一个更好的方法吗?
非常感谢你的帮助!
最佳答案
我会一次设置一个检查,以便您可以在评估之前检查变量是否存在。以下解决方案是否有效?
text_check = data.frame(id=test_df$id)
if('a' %in% colnames(test_df)){
text_check_temp = test_df %>% transmute(a=a>21)
text_check <- cbind(text_check, text_check_temp)
}
if('b' %in% colnames(test_df)){
text_check_temp = test_df %>% transmute(b=b>31)
text_check <- cbind(text_check, text_check_temp)
}
if('c' %in% colnames(test_df)){
text_check_temp = test_df %>% transmute(c=c>51)
text_check <- cbind(text_check, text_check_temp)
}
if('d' %in% colnames(test_df)){
text_check_temp = test_df %>% transmute(d=d>61)
text_check <- cbind(text_check, text_check_temp)
}
我试图通过循环转换检查来进一步重构代码,但无法弄清楚如何正确评估字符串公式。
杰森
关于R仅在列存在时验证数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37996061/