【问题标题】:Tidyverse and R: how to count rows in a tibble of a nested dataframeTidyverse 和 R:如何计算嵌套数据框的 tibble 中的行数
【发布时间】:2022-02-25 00:06:00
【问题描述】:

所以,我检查了多个帖子,但没有找到任何东西。根据this,我的代码应该可以工作,但事实并非如此。

目标:我想基本上打印出主题的数量——在这种情况下,这也是这个小标题中的行数。

代码:

 data<-read.csv("advanced_r_programming/data/MIE.csv")

make_LD<-function(x){
  LongitudinalData<-x%>%
    group_by(id)%>%
    nest()
  structure(list(LongitudinalData), class = "LongitudinalData")
}

print.LongitudinalData<-function(x){
  paste("Longitudinal dataset with", x[["id"]], "subjects")

}

x<-make_LD(data)

print(x)

这是我正在处理的数据集的头部:

> head(x)
[[1]]
# A tibble: 10 x 2
      id                  data
   <int>                <list>
 1    14 <tibble [11,945 x 4]>
 2    20 <tibble [11,497 x 4]>
 3    41 <tibble [11,636 x 4]>
 4    44 <tibble [13,104 x 4]>
 5    46 <tibble [13,812 x 4]>
 6    54 <tibble [10,944 x 4]>
 7    64 <tibble [11,367 x 4]>
 8    74 <tibble [11,517 x 4]>
 9   104 <tibble [11,232 x 4]>
10   106 <tibble [13,823 x 4]>

输出:

[1] "Longitudinal dataset with  subjects"

我已经尝试了上述 stackoverflow 帖子中的所有可能组合,但似乎都不起作用。

【问题讨论】:

  • 请使用dput显示数据集
  • 虽然我使用了head函数,但数据集是完整的。

标签: r oop tidyverse tibble


【解决方案1】:

这里有两个选项:

library(tidyverse)

# Create a nested data frame
dat = mtcars %>% 
  group_by(cyl) %>% 
  nest %>% as.tibble
    cyl               data
1     6  <tibble [7 x 10]>
2     4 <tibble [11 x 10]>
3     8 <tibble [14 x 10]>
dat %>% 
  mutate(nrow=map_dbl(data, nrow))

dat %>% 
  group_by(cyl) %>% 
  mutate(nrow = nrow(data.frame(data)))
    cyl               data  nrow
1     6  <tibble [7 x 10]>     7
2     4 <tibble [11 x 10]>    11
3     8 <tibble [14 x 10]>    14

【讨论】:

    【解决方案2】:

    在tidyverse中有一个具体的函数:n()

    你可以这样做:mtcars %&gt;% group_by(cyl) %&gt;% summarise(rows = n())

    > mtcars %>% group_by(cyl) %>% summarise(rows = n())
    # A tibble: 3 x 2
        cyl  rows
      <dbl> <int>
    1     4    11
    2     6     7
    3     8    14
    

    在更复杂的情况下,主题可能跨越多行(“长格式数据”),您可以这样做(假设 hp 表示主题):

    > mtcars %>% group_by(cyl, hp) %>% #always group by subject-ID last
    +   summarise(n = n()) %>% #observations per subject and cyl
    +   summarise(n = n()) #subjects per cyl (implicitly summarises across all group-variables except the last)
    `summarise()` has grouped output by 'cyl'. You can override using the `.groups` argument.
    # A tibble: 3 x 2
        cyl     n
      <dbl> <int>
    1     4    10
    2     6     4
    3     8     9
    

    请注意,最后一种情况下的n 比第一种情况要小,因为有相同数量的cylhp 现在被算作一个“主题”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-04
      • 2018-06-18
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      相关资源
      最近更新 更多