繁体   English   中英

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

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

我正在尝试定义一个函数,它需要两个参数,并且它将根据另一列(the_words)计算给定数据帧的列(morph_column)中括号的数量。 之后,我需要计算 Length 列中的观察次数,例如,如果为“the_words”返回的括号数为 1,我需要知道数据框中有多少项具有相同的 Length (1 )。 对 2,3,4,5... 等的观察也是如此。当我尝试在 dplyr 中使用 n() 时,它告诉我“ n()只能在 dplyr 动词中使用”,即使我正在使用summary和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())
   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM