首页 > 解决方案 > tidyverse 中的函数

问题描述

我是 tidyverse 的新手。我想创建具有中间功能的 tidyverse。我有一个结构

temp1 = sapply(df, function(x) .....)
temp2 = sapply(temp1, function(x) .......... )
temp3 = sapply(df, function(x) ..........)
temp = data.frame(temp2/temp3)

我想得到这样的东西

sapply(df, function(x) .......) %>% sapply(df, function(x) ....... )
 %>% ......

PS Ronak Shah 要求提供可重复的示例

df = data.frame(a = c(1,2,3), b = c(1,2,3))
temp1 = sapply(df, function(x) x*3)
temp2 = sapply(temp1, function(x) x+4 )
temp3 = sapply(df, function(x) x/4)
temp = data.frame(temp2/temp3)

标签: rtidyverse

解决方案


据我所知,管道操作员不记得链的第一个块,只记得前一个块,因此您必须使用中间步骤。

但是,您可以将代码的第一部分简化为管道:

temp1 = df %>% sapply(function(x) x*3) %>% sapply(function(x) x+4)
temp = temp1/sapply(df, function(x) x/4)

推荐阅读