如何在dplyr中基于ntile()-groups应用变异? [英] How to apply mutate based on ntile()-groups in dplyr?

查看:54
本文介绍了如何在dplyr中基于ntile()-groups应用变异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据类似的问题

I have tried finding answers based on similar questions

对于 tidyverse 来说是绝对新手,我有以下问题:如何估算每个 ntile()使用 dplyr

Being absolutely new to tidyverse, I have the following question: how can I estimate a median per ntile() using dplyr

# Data    
library(survival)
data(lung)

第一

p <- lung %>% mutate(test=ntile(inst,3))

所以现在

table(p$test)

 1  2  3 
76 76 75 

我想估算每个 p $ test

类似

p %>% mutate(test=ntile(inst,3), test.time=median(time[test %in% 1:3]))

其中没有提供我想要的。

Which did not provide what I sought.

推荐答案

我们可以使用'test'作为分组变量来计算中位数 of'time'

We can use the 'test' as a grouping variable to calculate the median of 'time'

library(dplyr)
lung %>% 
  group_by(test = ntile(inst, 3)) %>%
  mutate(test.time=median(time))

如果需要汇总的输出,则将 mutate 替换为 summary

If a summarised output is needed, then replace mutate with summarise

这篇关于如何在dplyr中基于ntile()-groups应用变异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆