【问题标题】:R tidyverse continuous approach for calculating ratio between 2 character variablesR tidyverse连续方法用于计算2个字符变量之间的比率
【发布时间】:2021-08-02 04:25:00
【问题描述】:

我一直在努力寻找使用pipes %>% 的连续tidyverse 方法来计算2 个字符变量之间的比率。 Tidyverse 方法应该只有 1 条使用 pipes %>% 的连续线。

这里是data frame

data <- data.frame(c('No', 'No', 'No', 'No', 'Yes', 'No'),
                c('No','Yes', 'No', 'Yes', 'Yes', 'No'))


colnames(data) <- c('smoke', 'diabetes')

data
#  smoke diabetes
#1    No       No
#2    No      Yes
#3    No       No
#4    No      Yes
#5   Yes      Yes
#6    No       No

对于R base,它很容易接近。计算吸烟人数与糖尿病患者人数之比

#'[R base approach for calculating ratio of the number of patients who are smoker to the number of patients who have diabetes]


count1 <- table(data$smoke)
count2 <- table(data$diabetes)

# Get the Ratio by dividing the counts
ratio <- count1 / count2
ratio
#       No       Yes 
#1.6666667 0.3333333 

但对于 tidyverse%&gt;% pipes 的方法,这令人困惑。

#'[Tidyverse 1 line with pipes %>% approach for calculating ratio of the number of patients who are smoker to the number of patients who have diabetes]
   
 data %>% group_by(smoke, diabetes) %>% 
      mutate(ratio = sum(smoke == 'Yes') / sum(diabetes == 'Yes'))
    
    # Groups:   smoke, diabetes [3]
    #  smoke diabetes ratio
    #  <chr> <chr>    <dbl>
    #1 No    No         NaN
    #2 No    Yes          0
    #3 No    No         NaN
    #4 No    Yes          0
    #5 Yes   Yes          1
    #6 No    No         NaN

在这里你可以看到我无法得到与R base 方法相同的比率。 我怎么解决这个问题?我应该使用case_when()吗?

谢谢。

【问题讨论】:

    标签: r dplyr group-by tidyverse


    【解决方案1】:

    我们不是按两列分组,而是用summariseacross 得到“是”的计数,然后返回两列的“比率”

    library(dplyr)
    data %>% 
      summarise(across(everything(), ~ sum(. == 'Yes'))) %>% 
      mutate(ratio = diabetes/smoke)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2017-06-05
      • 2017-05-24
      相关资源
      最近更新 更多