![](/img/trans.png)
[英]How to count number of observations in each column in a grouped dataframe in 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.