如何使用 R 提供自定义匹配参数来比较代码列表模式?
How to give custom matching parameters to compare code list pattern using R?
我想比较数据框列的匹配和不匹配。在这里,我在 a 列中有代码,在 b 列中有它们的值。如果 a 列有 1 并且 b 列有男性(1 = 男性和 2 = 女性)行,我想得到匹配,同样如果给定的代码不满足,应该存在不匹配。
if 1=male or 2=female then match else mismatch
下面是我尝试过的代码,它适用于简单的模式匹配或精确值匹配,但我希望它能与代码列表一起使用
ABData <- data.frame(a = c(1,2,1,1,2),
b = c("Male","Female","Male","Male","Male")
match<- ABData %>% rowwise() %>% filter(grepl(a,b))
mismatch<- ABData %>% rowwise() %>% filter(!grepl(a,b))
预期输出:
Match
a expected actual
1 Male Male
2 Female Female
1 Male Male
1 Male Male
Mismatch
a expected actual
2 Female Male
您可以为子集创建索引:
inds <- with(ABData, a == 1 & b == 'Male' | a == 2 & b == 'Female')
match_df <- subset(ABData, inds)
mismatch_df <- subset(ABData, !inds)
然后我们添加 actual
列。
match_df <- transform(match_df, actual = b)
mismatch_df <- transform(mismatch_df, actual = ifelse(b == 'Male','Female', 'Male'))
我想比较数据框列的匹配和不匹配。在这里,我在 a 列中有代码,在 b 列中有它们的值。如果 a 列有 1 并且 b 列有男性(1 = 男性和 2 = 女性)行,我想得到匹配,同样如果给定的代码不满足,应该存在不匹配。
if 1=male or 2=female then match else mismatch
下面是我尝试过的代码,它适用于简单的模式匹配或精确值匹配,但我希望它能与代码列表一起使用
ABData <- data.frame(a = c(1,2,1,1,2),
b = c("Male","Female","Male","Male","Male")
match<- ABData %>% rowwise() %>% filter(grepl(a,b))
mismatch<- ABData %>% rowwise() %>% filter(!grepl(a,b))
预期输出:
Match
a expected actual
1 Male Male
2 Female Female
1 Male Male
1 Male Male
Mismatch
a expected actual
2 Female Male
您可以为子集创建索引:
inds <- with(ABData, a == 1 & b == 'Male' | a == 2 & b == 'Female')
match_df <- subset(ABData, inds)
mismatch_df <- subset(ABData, !inds)
然后我们添加 actual
列。
match_df <- transform(match_df, actual = b)
mismatch_df <- transform(mismatch_df, actual = ifelse(b == 'Male','Female', 'Male'))