【问题标题】:How to count observations per ID in R? (and obtain mean and standard deviation)如何计算 R 中每个 ID 的观察值? (并获得平均值和标准差)
【发布时间】:2021-06-01 23:50:31
【问题描述】:

我有一个数据集,参与者为一个关键变量记录了不同数量的观察数据点(例如,一些测量了 5 天,另一些测量了 7 天)。我想计算参与者被测量的天数,以及标准偏差。我尝试使用 count 功能,但对我来说不起作用。

我的数据如下所示:

*Participant_Id    OBSvalue
001             8574
001             9757
001             8487
002             11202
002             13949
003             10203
004             8963*

我想得到类似的东西:

*Mean number of observation for participants: 2.4
Standard deviation: 0.5*

提前谢谢你!

最好的

【问题讨论】:

    标签: r count mean


    【解决方案1】:

    这很简单。

    library(tidyverse)
    
    # Create a data frame / tibble
    data <- tribble(
              ~Participant_Id, ~OBSvalue,
              "001",             8574,
              "001",            9757,
              "001",             8487,
              "002",             11202,
              "002",             13949,
              "003",             10203,
              "004",             8963
            )
    
    # Caluclate summary statistics by participant
    summary <- data %>% 
                 group_by(Participant_Id) %>% 
                 summarise(
                   N=n(),
                   Mean=mean(OBSvalue),
                   SD=sd(OBSvalue),
                   .groups="drop"
                 )
    summary
    
    # Calculate mean number of values per participant
    summary %>% summarise(MeanN=mean(N), .groups="drop")
    

    给予

      Participant_Id     N   Mean    SD
      <chr>          <int>  <dbl> <dbl>
    1 001                3  8939.  709.
    2 002                2 12576. 1942.
    3 003                1 10203    NA 
    4 004                1  8963    NA 
    

    # A tibble: 1 x 1
      MeanN
      <dbl>
    1  1.75
    

    This site 是学习 R 语言基础数据科学的绝佳起点。

    【讨论】:

      【解决方案2】:

      您可以使用table,然后使用meansd

      mean(table(x[1]))
      #[1] 1.75
      > sd(table(x[1]))
      #[1] 0.9574271
      

      数据:

      x <- read.table(header=TRUE, text="Participant_Id    OBSvalue
      001             8574
      001             9757
      001             8487
      002             11202
      002             13949
      003             10203
      004             8963")
      

      【讨论】:

        【解决方案3】:
        require(data.table)
        x <- data.table(
          Participant_Id = c("001",  "001",  "001",  "002",  "002",  "003",  "004"),
          OBSvalue = c(8574, 9757, 8487, 11202, 13949, 10203, 8963)
        )
        # mean of count of Participant_Id
        x[, .N, by = Participant_Id][, mean(N)]
        # sd of count of Participant_Id
        x[, .N, by = Participant_Id][, sd(N)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-01
          • 2018-06-18
          • 1970-01-01
          • 2014-03-21
          • 2020-06-24
          • 2020-09-01
          相关资源
          最近更新 更多