Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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
Str_计数:NAs问题和相似单词的多次出现_R - Fatal编程技术网

Str_计数:NAs问题和相似单词的多次出现

Str_计数:NAs问题和相似单词的多次出现,r,R,我想使用str_count函数计算列中某些字符串的出现次数。它适用于只包含正确表达式的行。 但是,对于包含一个NA的行,我得到的结果是NA,我的列包含很多NAs 我尝试使用tidyverse的summary函数执行此任务失败,它使用sum函数和%in%运算符以及常规比较。到目前为止,Sum和Stru count给了我最有希望的结果 # library(tidyverse) # Reproducible data frame similar to the one I am working on

我想使用str_count函数计算列中某些字符串的出现次数。它适用于只包含正确表达式的行。 但是,对于包含一个NA的行,我得到的结果是NA,我的列包含很多NAs

我尝试使用tidyverse的summary函数执行此任务失败,它使用sum函数和%in%运算符以及常规比较。到目前为止,Sum和Stru count给了我最有希望的结果

# library(tidyverse)

# Reproducible data frame similar to the one I am working on
# This should resemble long data for two participants, that each have two 
# codes in a column
test <- data.frame(name = c("A1", "A1", "B1", "B1"), code_2 = c("SF08", "SF03", "SF03", NA))

# Here is my analysis that counts the number of matches of a code
analysis <- test %>% 
  group_by(name) %>% 
  summarize(
       total_sf2 = sum(stringr::str_count(code_2, "SF"))
       )
#库(tidyverse)
#可复制的数据框与我正在处理的数据框相似
#这应该类似于两个参与者的长数据,每个参与者有两个
#列中的代码
测试%
总结(
总sf2=总和(stringr::str_计数(代码为“SF”))
)

我希望参与者A1有两个匹配项(我得到),参与者B2有一个匹配项而不是结果NA

test %>% 
   group_by(name) %>% 
   summarize(
     total_sf2 = sum(stringr::str_count(code_2, "SF"), na.rm=TRUE)
   )

# A tibble: 2 x 2
#  name  total_sf2
#  <fct>     <int>
#1 A1            2
#2 B1            1
测试%>%
分组单位(名称)%>%
总结(
总计sf2=总和(stringr::str_计数(代码“SF”),na.rm=TRUE)
)
#一个tibble:2x2
#名称总计\u sf2
#       
#1 A1 2
#2 B1 1

在base R中,您可以在
聚合中使用
regexpr
,它不受
s的影响

aggregate(code_2 ~ name, test, function(x) sum(regexpr("SF", x)))
#   name code_2
# 1   A1      2
# 2   B1      1

使用
grepl
data.table

library(data.table)
setDT(test)[, .(code_2 = sum(grepl("SF", code_2))), name]
#   name code_2
#1:   A1      2
#2:   B1      1