【问题标题】:Word count across subset of columns in one new column一个新列中列子集的字数
【发布时间】:2022-10-23 18:38:39
【问题描述】:

我有以下数据框:

structure(list(g = c("1", "2", "3"), x = c("This is text.", "This is text too.", 
"This is no text"), y = c("What is text?", "Can it eat text?", 
"Maybe I will try.")), class = "data.frame", row.names = c(NA, 
-3L))

我想计算xy 列中的单词数,并将该值相加得到一列,其中包含每列使用的总单词数。重要的是我能够对数据进行子集化。结果应如下所示:

structure(list(g = c("1", "2", "3"), x = c("This is text.", "This is text too.", 
"This is no text"), y = c("What is text?", "Can it eat text?", 
"Maybe I will try."), z = c("6", "8", "8")), class = "data.frame", row.names = c(NA, 
-3L))

我尝试将str_count(" ") 与不同的正则表达式结合使用acrossapply,但我似乎没有得到解决方案。

在我最初的问题中,我没有预料到其中包含NA 单元格的列会出现问题,但我确实做到了。因此,任何解决方案都需要能够处理NA 单元格。

【问题讨论】:

    标签: r


    【解决方案1】:

    这里使用tokenizers的解决方案:

    library(tokenizers)
    
    df <- 
      structure(list(g = c("1", "2", "3"), x = c("This is text.", "This is text too.", 
      "This is no text"), y = c("What is text?", "Can it eat text?", 
      "Maybe I will try.")), class = "data.frame", row.names = c(NA, 
      -3L))
    
    df$z = tokenizers::count_words(df$x) + tokenizers::count_words(df$y)
    
    df
    #>   g                 x                 y z
    #> 1 1     This is text.     What is text? 6
    #> 2 2 This is text too.  Can it eat text? 8
    #> 3 3   This is no text Maybe I will try. 8
    

    如果您更喜欢纯 R:

    df$z <- rowSums(
      sapply(df[,c("x","y")],function(x)  
        sapply(gregexpr("\b\w+\b", x) , function(x) 
          if(x[[1]] > 0) length(x) else 0)))
    
    

    请注意,w+ 匹配所有单词, 匹配单词边界,尽管我相信“w”就足够了

    【讨论】:

    • 感谢您对 tokenizer 包的建议!它看起来真的很酷。这两种解决方案中的任何一种都能够处理NA 列吗?
    【解决方案2】:

    一种可能的解决方案:

    df$z = stringi::stri_count_words(paste(df$x, df$y))
    
      g                 x                 y z
    1 1     This is text.     What is text? 6
    2 2 This is text too.  Can it eat text? 8
    3 3   This is no text Maybe I will try. 8
    

    或者

    df$z = lengths(gregexpr("\b\w+\b", paste(df$x, df$y)))
    

    【讨论】:

    • 谢谢,stringi 对我来说就像一个魅力,可以处理NAs。
    【解决方案3】:

    您可以使用str_split,然后计算结果的长度。 为简单起见,我添加了 xy 列,其中包含 x 和 y 的组合词:

    my_df <- my_df %>% mutate(xy= paste(x, y))
    z <- c(rep(0, length(my_df$xy)))
    for (i in 1:length(my_df$xy)) z[i]<-length(str_split_fixed(my_df$xy[i], " ", Inf))
    cbind(my_df, z)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2020-12-15
      • 1970-01-01
      • 2019-07-20
      相关资源
      最近更新 更多