R:验证具有不同长度的数值变量的数据
R: Validate Data for Numeric Variables with Different Length
这是我的数据框
Key Q1 Q2
1 1 NA
2 2 1
3 8 NA
4 3 2
5 1 32
6 5 3
我想验证数据是否符合规则
规则 1:
if Q1==1, Q2 can only have 1 & 2
规则 2:
if Q1!=1, Q2 has to be empty/without any value
我想要如下所示的结果:
Key Q1 Q2 Result
1 1 NA TRUE
2 2 1 TRUE
3 8 NA FALSE
4 3 2 TRUE
5 1 32 FALSE
6 5 3 FALSE
但是,我收到警告错误 "the condition has length > 1 and only the first element will be used"。
我们可以做到
with(df1, (Q1==1) & (Q2 %in% 1:2)|(Q1 != 1 & is.na(Q2)))
这是我的数据框
Key Q1 Q2
1 1 NA
2 2 1
3 8 NA
4 3 2
5 1 32
6 5 3
我想验证数据是否符合规则
规则 1:
if Q1==1, Q2 can only have 1 & 2
规则 2:
if Q1!=1, Q2 has to be empty/without any value
我想要如下所示的结果:
Key Q1 Q2 Result
1 1 NA TRUE
2 2 1 TRUE
3 8 NA FALSE
4 3 2 TRUE
5 1 32 FALSE
6 5 3 FALSE
但是,我收到警告错误 "the condition has length > 1 and only the first element will be used"。
我们可以做到
with(df1, (Q1==1) & (Q2 %in% 1:2)|(Q1 != 1 & is.na(Q2)))