R中的表操作-dplyr / tidyverse解决方案

莱布

我正在尝试将一个df转换为另一种格式。

开始df:

df <- data.frame(id = c("1", "2", "3","4", "5", "6", "7", "8", "9", "10"),
    criteria_A = c("present", "present", "absent", "absent", "absent", "present", "absent", "present", "absent", "present"),
    criteria_B =c("absent", "absent", "present", "absent", "absent", "present", "absent", "absent", "present", "present"))

我想按当前/不存在来计数每个标准,并重新列出:

df2 <- data.frame(criteria = c("criteria_A", "criteria_A", "criteria_B", "criteria_B"),
    count = c("5", "5", "4", "6"),
    status = c("present", "absent", "present", "absent"))

我考虑过按标准以这种方式获取计数:

library(dplyr)
tmp1 <- df %>% group_by(criteria_A) %>% count() %>% mutate(criteria="criteria_A")
tmp1 <- tmp1 %>% rename(criteria_A=status)
tmp2 <- df %>% group_by(criteria_B) %>% count() %>% mutate(criteria="criteria_B")
tmp2 <- tmp2 %>% rename(criteria_B=status)

我想我可以然后垂直合并输出。当我实际上有数百个条件时,这不是一种有效或聪明的方法。

我敢肯定有一个优雅的解决方案,我不够聪明,无法弄清楚!

我们将一如既往地向您提供任何帮助。

尼洛克

您可以使用dplyr::tally将数据旋转为长格式后尝试使用pivot_longer

library(dplyr)

df %>%
  pivot_longer(-id, 
               names_to = 'criteria',
               values_to = 'status') %>%
  group_by(criteria, status) %>%
  tally

#----
  criteria   status      n
  <chr>      <chr>   <int>
1 criteria_A absent      5
2 criteria_A present     5
3 criteria_B absent      6
4 criteria_B present     4

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在R中的嵌套for循环情况下寻找适用的,tidyr或dplyr解决方案

来自分类Dev

Case_when使用sum对数据进行分类时-R / dplyr解决方案

来自分类Dev

用于DPLYR分辨率的R Data.Table解决方案

来自分类Dev

Case_when使用sum对数据进行分类时-R / dplyr解决方案

来自分类Dev

在分组的行中使用case_when()并选择何时显示项目-tidyverse / R解决方案

来自分类Dev

基于单独列中的两个因子级别的行值差异的Dplyr解决方案

来自分类Dev

PrefixAgainbat中的解决方案

来自分类Dev

表中的日志解决方案

来自分类Dev

线性模型和DPLyr-更好的解决方案?

来自分类Dev

R中的Uniroot解决方案

来自分类Dev

哈希表冲突检测解决方案

来自分类Dev

R DataTable解决方案快速重塑

来自分类Dev

模拟$ dialog中的解决方案

来自分类Dev

解决方案中的参考损坏

来自分类Dev

在pyjade解决方案中包括mixins

来自分类Dev

Java中的高效编程解决方案

来自分类Dev

芝麻中的BNode解决方案

来自分类Dev

Perl中更好的Regex解决方案?

来自分类Dev

C ++中多重定义的解决方案

来自分类Dev

Prolog中sum的解决方案

来自分类Dev

多租户解决方案中的PostSharp

来自分类Dev

Perl中更好的Regex解决方案?

来自分类Dev

C ++中多重定义的解决方案

来自分类Dev

无法在解决方案中调试项目

来自分类Dev

验证解决方案中的.csproj文件

来自分类Dev

Swift中的重构解决方案

来自分类Dev

hackerrank中的解决方案不匹配

来自分类Dev

了解 c 中的背包解决方案

来自分类Dev

在 main 中调用解决方案类