按变量分组计算有效/非NA观测值的数量。

huangapple go评论88阅读模式
英文:

Count valid/non-NA observations grouped by variable

问题

我已经谷歌了大约两个小时,试图找到一个简单问题的解决方案,但是我一无所获。我甚至找不到正确的函数来实现我想要的结果,所以我不得不求助,尽管这似乎是一个非常基本的问题。

我有一个跨越多个国家的调查,我正在创建一个包含从数据中派生的统计数据的数据框(例如给定变量的国家均值)。

假设数据框 df 看起来像这样:

  1. country <- c(1,1,1,1,1,1,2,2,2,2,2,2)
  2. var <- c(1,NA,2,1,2,2,3,3,1,3,4,NA)
  3. df <- cbind.data.frame(country, var)

我可以很容易地计算名义 n 的数量:

  1. df %>% group_by(country) %>% summarize(n=n())

但是如何计算变量 var 上的有效观测值的数量呢?

英文:

I have been googling for about two hours now trying to find the solution to a simple problem, but I am not getting anywhere. I am not even finding the right function I could use to get where I want to get, so I have to resort to asking for help even though it seems a very basic question.

I have a survey spanning various countries, and I am in the process of creating a dataframe with statistics derived from the data (such as national mean on a given variable).

Let's say the dataframe df looks like this:

  1. country &lt;- c(1,1,1,1,1,1,2,2,2,2,2,2)
  2. var &lt;- c(1,NA,2,1,2,2,3,3,1,3,4,NA)
  3. df &lt;- cbind.data.frame(country, var)

I can easily count the nominal n's:

  1. df %&gt;% group_by(country) %&gt;% summarize(n=n())

But how do I count valid observations on the variable var?

答案1

得分: 2

任何一个都可以。group_by()/summarise()/n()这三个函数调用可以被一个函数count()替代。

  1. country <- c(1,1,1,1,1,1,2,2,2,2,2,2)
  2. var <- c(1,NA,2,1,2,2,3,3,1,3,4,NA)
  3. df <- cbind.data.frame(country, var)
  4. suppressPackageStartupMessages(
  5. library(dplyr)
  6. )
  7. df %>%
  8. na.exclude() %>%
  9. count(country)
  10. #> country n
  11. #> 1 1 5
  12. #> 2 2 5
  13. df %>%
  14. na.omit() %>%
  15. count(country)
  16. #> country n
  17. #> 1 1 5
  18. #> 2 2 5
  19. df %>%
  20. tidyr::drop_na() %>%
  21. count(country)
  22. #> country n
  23. #> 1 1 5
  24. #> 2 2 5

创建于2023-08-08,使用 reprex v2.0.2

英文:

Any of these will do it.
Three function calls, group_by()/summarise()/n() can be replaced by one only, count().

  1. country &lt;- c(1,1,1,1,1,1,2,2,2,2,2,2)
  2. var &lt;- c(1,NA,2,1,2,2,3,3,1,3,4,NA)
  3. df &lt;- cbind.data.frame(country, var)
  4. suppressPackageStartupMessages(
  5. library(dplyr)
  6. )
  7. df %&gt;%
  8. na.exclude() %&gt;%
  9. count(country)
  10. #&gt; country n
  11. #&gt; 1 1 5
  12. #&gt; 2 2 5
  13. df %&gt;%
  14. na.omit() %&gt;%
  15. count(country)
  16. #&gt; country n
  17. #&gt; 1 1 5
  18. #&gt; 2 2 5
  19. df %&gt;%
  20. tidyr::drop_na() %&gt;%
  21. count(country)
  22. #&gt; country n
  23. #&gt; 1 1 5
  24. #&gt; 2 2 5

<sup>Created on 2023-08-08 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年8月8日 22:54:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定