结合嵌套在tibble中的列表

发布于 2025-02-13 14:00:01 字数 803 浏览 0 评论 0原文

我想计算一个表中包含几个从...到以下对的几个的唯一值数量:

tmp <- tribble(
  ~group, ~from, ~to,
       1,     1,  10,
       1,     5,   8,
       1,    15,  20,
       2,     1,  10,
       2,     5,  10,
       2,    15,  18
)

我尝试将所有值嵌套在每行(工作)的列表中,但是将这些嵌套列表组合到一个向量中并计数这些唯一内容无法正常工作。

tmp %>%
  group_by(group) %>%
  rowwise() %>%
  mutate(nrs = list(c(from:to))) %>%
  summarise(n_uni = length(unique(unlist(list(nrs)))))

所需的输出看起来像这样:

tibble(group = c(1, 2),
       n_uni = c(length(unique(unlist(list(tmp$nrs[tmp$group == 1])))),
                 length(unique(unlist(list(tmp$nrs[tmp$group == 2]))))))

# # A tibble: 2 × 2
#    group n_uni
#    <dbl> <int>
#1     1    16
#2     2    14

任何帮助都将不胜感激!

I want to count the number of unique values in a table that contains several from...to pairs like below:

tmp <- tribble(
  ~group, ~from, ~to,
       1,     1,  10,
       1,     5,   8,
       1,    15,  20,
       2,     1,  10,
       2,     5,  10,
       2,    15,  18
)

I tried to nest all values in a list for each row (works), but combining these nested lists into one vector and counting the uniques doesn't work as expected.

tmp %>%
  group_by(group) %>%
  rowwise() %>%
  mutate(nrs = list(c(from:to))) %>%
  summarise(n_uni = length(unique(unlist(list(nrs)))))

The desired output looks like this:

tibble(group = c(1, 2),
       n_uni = c(length(unique(unlist(list(tmp$nrs[tmp$group == 1])))),
                 length(unique(unlist(list(tmp$nrs[tmp$group == 2]))))))

# # A tibble: 2 × 2
#    group n_uni
#    <dbl> <int>
#1     1    16
#2     2    14

Any help would be much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

方圜几里 2025-02-20 14:00:01
tmp %>% 
  rowwise() %>% 
  mutate(nrs = list(from:to)) %>% 
  group_by(group) %>% 
  summarise(n_uni = n_distinct(unlist(nrs)))

OP的方法的问题是rowwise等同于新分组,它删除了初始group_by step。因此,在创建创建nrs之后,我们必须在group_by 中进行rowwise step。

tmp %>% 
  rowwise() %>% 
  mutate(nrs = list(from:to)) %>% 
  group_by(group) %>% 
  summarise(n_uni = n_distinct(unlist(nrs)))

The issue with OP's approach is that rowwise is the equivalent of a new grouping, that drops the initial group_by step. Thus we've got to group_by after creating nrs in the rowwise step.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文