R count times word appears in element of list

前端 未结 4 681
误落风尘
误落风尘 2020-12-20 04:51

I have a list comprised of words.

> head(splitWords2)
[[1]]
 [1] \"Some\"        \"additional\"  \"information\" \"that\"        \"we\"          \"would\"         


        
4条回答
  •  孤城傲影
    2020-12-20 05:25

    For one specific word:

    words <- list(a = c("a","b","c","a","a","b"), b = c("w","w","q","a"))
    $a
    [1] "a" "b" "c" "a" "a" "b"
    
    $b
    [1] "w" "w" "q" "a"
    wt <- data.frame(lineNum = 1:length(words))
    wt$count <- sapply(words, function(x) sum(str_count(x, "a")))
      lineNum count
    1       1     3
    2       2     1
    

    If vector w contains words that you want to count:

    w <- c("a","q","e")
    allwords <- lapply(w, function(z) data.frame(lineNum = 1:length(words), 
                count = sapply(words, function(x) sum(str_count(x, z)))))
    names(allwords) <- w
    $a
      lineNum count
    a       1     3
    b       2     1
    
    $q
      lineNum count
    a       1     0
    b       2     1
    
    $e
      lineNum count
    a       1     0
    b       2     0
    

提交回复
热议问题