[英]Couple a function inside mutate dplyr r: Calculate second derivative
I would like to calculate the following formula on all my data grouped_by(id)
我想对所有数据
grouped_by(id)
计算以下公式
$$\frac{y''}{((1+(y')^2)^{3/2}}$$
I'm getting stuck on passing a function through mutate because it gives me unequal column sizes. 我陷入了通过mutate传递函数的困境,因为它给了我不相等的列大小。
Sample data is: 样本数据为:
require(dplyr)
df<-data.frame(Time=seq(65),
SkinTemp=rnorm(65,37,0.5),
id=rep(1:10,c(5,4,10,6,7,8,9,8,4,4)))
First derivative (OK): 一阶导数(确定):
df <-df %>% group_by(id) %>% filter(n() > 1) %>%
mutate(first_d = SkinTemp - lag(SkinTemp))
df<-as.data.frame(df) #Back to data frame
Second derivative (stuck): 二阶导数(卡住):
drv <- function(x, y) diff(y) / diff(x) #Defined this to pass to mutate
middle_pts <- function(x) x[-1] - diff(x) / 2
second_d <-df %>% group_by(id) %>%
mutate(second_d = drv(middle_pts(Time), drv(Time, SkinTemp)))
The diff
returns a vector of length one less than the original vector
. diff
返回一个长度比原始vector
短一向量的vector
。 The function mutate
requires the column to return the same length. 函数
mutate
要求列返回相同的长度。 Therefore, we need to do some appending with NA
or value of choice 因此,我们需要对
NA
或选择值做一些补充
drv <- function(x, y) c(NA, (diff(y) /diff(x)))
middle_pts <- function(x) c(NA, (x[-1] - diff(x) /2))
Now, the OP's code should work 现在,OP的代码应该可以正常工作
df %>%
group_by(id) %>%
mutate(second_d = drv(middle_pts(Time), drv(Time, SkinTemp)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.