【发布时间】: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 与 %>% 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