在 R 中定义函数时如何计算列中的观察次数?

How to count the number of observations in a column while defining a function in R?

我正在尝试定义一个函数,它将接受两个参数,并且它将根据另一列([=15)计算给定数据框的列(morph_column)中的括号数=]).之后,我需要计算 Length 列内的观察次数,例如,如果为“the_words”返回的括号数为 1,我需要知道数据框中有多少项带有相同的长度 (1)。对 2、3、4、5 等的观察也是如此。 当我尝试在 dplyr 中使用 n() 执行此操作时,它告诉我“n() 只能在 dplyr 动词内部使用”,即使我正在使用 summarize 和 group_by 执行此操作。我怎样才能解决这个问题?谢谢你。 这是代码:

morphemes_per_word <- function(the_words, morph_column) {
    result <- data.frame("Word" = the_words, "Length" = (stri_count_regex(morph_column, "\[")))
    result2 <- result %>%
      dplyr::group_by(Length)
      dplyr::summarise(N = n())
    return(result2)
}

group_by 步骤和 summarise

之间的链条 (%>%) 中断
morphemes_per_word <- function(the_words, morph_column) {
    result <- data.frame(Word = the_words,
         Length = stri_count_regex(morph_column, "\["))
    result %>%
      dplyr::group_by(Length) %>%
      dplyr::summarise(N = n())
   
}