Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何删除dataframe中的行并基于匹配的字符值求和数值_R_Regex_Sum - Fatal编程技术网

如何删除dataframe中的行并基于匹配的字符值求和数值

如何删除dataframe中的行并基于匹配的字符值求和数值,r,regex,sum,R,Regex,Sum,我有一个包含单词频率的数据框,其中许多只是一个相同首字母单词的拼写变体,例如首字母oh,如下示例数据: test <- data.frame( Word = c("oh", "ooh", "ohhh", "right-oh", "o'clock", "oohh", "o-oh", "o-b-i-t-r-y"), Freq = c(4762, 554, 15, 7, 7, 3, 3, 2), c5 = c("ITJ", "ITJ", "NP0", "ZZ0", "NN1", "I

我有一个包含单词频率的数据框,其中许多只是一个相同首字母单词的拼写变体,例如首字母
oh
,如下示例数据:

test <- data.frame(
  Word = c("oh", "ooh", "ohhh", "right-oh", "o'clock", "oohh", "o-oh", "o-b-i-t-r-y"),
  Freq = c(4762, 554, 15, 7, 7, 3, 3, 2),
  c5 = c("ITJ", "ITJ", "NP0", "ZZ0", "NN1", "ITJ", "AV0", "ZZ0"),
  Freq_BNCc = c(41555, 3856, 21, 931, 10, 8, 1065, 6),
  stringsAsFactors = F)

test
         Word Freq  c5 Freq_BNCc
1          oh 4762 ITJ     41555
2         ooh  554 ITJ      3856
3        ohhh   15 NP0        21
4    right-oh    7 ZZ0       931
5     o'clock    7 NN1        10
6        oohh    3 ITJ         8
7        o-oh    3 AV0      1065
8 o-b-i-t-r-y    2 ZZ0         6
然后,通过将标题词的频率加上
test
中两列中的变体相加,更新
test2
中的频率:

test2$Freq[test2$Word=="oh"] <- sum(test$Freq[grepl("^o[oh-]+$", test$Word)])
test2$Freq_BNCc[test2$Word=="oh"] <- sum(test$Freq_BNCc[grepl("^o[oh-]+$", test$Word)])

但这种方法感觉笨拙而且容易出错。有更好的方法吗?

正如我在上面的评论中所写的,简单地用目标词替换变体可能更容易,使用
word
进行分组,然后使用
dplyr::mutate
按组对相关值求和,并使用
dplyr::slice
获得第一个组成员:

库(dplyr)
#用目标词替换变体。
test[grepl((?!^oh$)^o[oh-]+$,test$Word,perl=T),“Word”]%
分组依据(字)%>%
变异(Freq=sum(Freq),Freq_-BNCc=sum(Freq_-BNCc))%>%
切片(1)
####输出####
#一个tibble:4x4
#分组:Word[4]
字频c5频
1 o-b-i-t-r-y 2 ZZ06
下午2时7分10分
3 oh 5337 ITJ 46505
4右oh 7 ZZ0 931

就我个人而言,我更喜欢字符串距离而不是正则表达式,因此我可能会使用
test[stringdist(“哦”,test$Word,“cosine”)<.2,“Word”]您是否尝试过使用字符串相似性度量,例如cosine,等等?不,但是匹配变量不是问题。对于
oh
的第一个条目,您的正则表达式返回FALSE,您是指这个正则表达式吗
grepl((?!^oh$)^o[oh-]+$”,test$Word,perl=T)
。这是有意的,因为我想删除带有变体的行,但不想删除带有head单词的行,但您不想删除它们。你想把它们加起来,得到总数……对吗?这与移除不同。如果您使正则表达式包含原始的
oh
,那么您可以使用它创建组,并根据usualThanks对每个组求和,做得很好。我不熟悉字符串距离和相似性度量,但如果它们能够比正则表达式更好地处理我的数据(来自非正式对话语料库)的巨大差异,我会感到惊讶。
test2$Freq[test2$Word=="oh"] <- sum(test$Freq[grepl("^o[oh-]+$", test$Word)])
test2$Freq_BNCc[test2$Word=="oh"] <- sum(test$Freq_BNCc[grepl("^o[oh-]+$", test$Word)])
test2
         Word Freq  c5 Freq_BNCc
1          oh 5337 ITJ     46505
4    right-oh    7 ZZ0       931
5     o'clock    7 NN1        10
8 o-b-i-t-r-y    2 ZZ0         6