本文介绍了R:使用dplyr :: mutate / dplyr :: transmute与一个整行行为的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个数据框。为了争论的缘故,我们假设这是数据帧 datasets :: women 。我想通过对每一行应用一个函数从框架创建一个向量。 似乎通常的方法是使用 dplyr ,并调用 mutate 或 transmute ,例如: dplyr :: transmute(women,some_index = 2 * height + weight) 很棒:这个工作。 但是,如果我将 some_index 的计算推出到一行作用于一行的函数: calc_some_index 2 * woman $ height + woman $ weight } pre> 有没有办法我应该调用 mutate / transmute 这样就可以在其输入的每一行调用这个函数? 当然,如果我调用 $,我可以看到我得到正确的结果b $ b dplyr :: transmute(women,some_index = calc_some_index(women)) 但我相信这只是通过将计算出的向量预先计算到变态调用中来欺骗。它不工作,例如,如果我打电话: dplyr :: transmute(head(women,n = 10) ,some_index = calc_some_index(women)) 解决方案 '/> 如果我这样做 图书馆(dplyr) transpute(头(女,n = 10), some_index = calc_some_index(头(女,10))) 然后它工作(你的代码中的错误抱怨大小不同) 或者,您可以使用管道它的作用是: head(women,10)%>% transmute(calc_some_index(。)) I have a data frame. For argument's sake, let's say it's the datasets::women data frame. I want to create a vector from the frame by applying a function to each row.It seems that the usual way to do this is to use dplyr and call mutate or transmute, for example:dplyr::transmute(women, some_index = 2 * height + weight)Great: that works.But what if I pull out the calculation of some_index into a function which acts on a row:calc_some_index <- function(woman) { 2 * woman$height + woman$weight}Is there a way I should call mutate/transmute so that it calls this function on each row of its input?Of course, I can see that I get the right result if I call dplyr::transmute(women, some_index=calc_some_index(women))but I believe this is just 'cheating' by subbing the calculated vector in, pre-calculated, to the transmute call. It doesn't work, for instance, if I call:dplyr::transmute(head(women, n=10), some_index=calc_some_index(women)) 解决方案 I think you're incurring in a dimension error.If I dolibrary(dplyr)transmute(head(women, n=10), some_index=calc_some_index(head(women,10)))Then it works (the error in your code complained about sizes differing)Alternatively, you could use the pipe and it works:head(women, 10) %>% transmute(calc_some_index(.)) 这篇关于R:使用dplyr :: mutate / dplyr :: transmute与一个整行行为的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 07:40