我有一个xy
data.frame
,以及其他factor
,例如:
df <- data.frame(y = c(0.05, -0.03, -0.13, -0.24, 0.05, -0.03, -0.13, -0.24, 0.59, 1.97, 2.26, 1.89, 0.59, 1.97, 2.26, 1.89),
x = c(0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58),
sex = c('F', 'F', 'F', 'F', 'M', 'M', 'M', 'M', 'F', 'F', 'F', 'F', 'M', 'M', 'M', 'M'),
group = c('B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'))
我正在寻找一个function
(可能dplyr
的用法最好),它将计算df
中每个因子的每个级别的斜率( x
的差值除以每对连续x
点之间的差值df
)。在本例中,我将有4组坡度:对于group = A
和sex = F
,对于group = A
和sex = M
,对于group = B
和sex = F
,对于group = B
和sex = M
。
如果可能的话,如果解决方案是通用的,以便它应用于比本例中指定的更多的factors
(条件是所有因子都属于factor
类),那就更好了。
有什么想法吗?
发布于 2018-09-02 22:43:28
为了使用dplyr
找到斜率(根据您的定义),可能需要使用lag()
函数。
lead
和lag
函数:
查找向量中的“下一个”或“前一个”值。用于比较当前值之前或之后的值。
为了实现按因子变量分组,您可以首先使用dplyr::group_by()
。这是可泛化的,可以接受一个或多个分组变量。
下面是一个可重复的示例,显示了每个组的计算。
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- data.frame(y = c(0.05, -0.03, -0.13, -0.24, 0.05, -0.03, -0.13, -0.24, 0.59, 1.97, 2.26, 1.89, 0.59, 1.97, 2.26, 1.89),
x = c(0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58, 0, 1.58, 2, 4.58),
sex = c('F', 'F', 'F', 'F', 'M', 'M', 'M', 'M', 'F', 'F', 'F', 'F', 'M', 'M', 'M', 'M'),
group = c('B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'))
df %>%
group_by(sex, group) %>%
mutate(slope = (y - lag(y)) / (x - lag(x)))
#> # A tibble: 16 x 5
#> # Groups: sex, group [4]
#> y x sex group slope
#> <dbl> <dbl> <fct> <fct> <dbl>
#> 1 0.0500 0. F B NA
#> 2 -0.0300 1.58 F B -0.0506
#> 3 -0.130 2.00 F B -0.238
#> 4 -0.240 4.58 F B -0.0426
#> 5 0.0500 0. M B NA
#> 6 -0.0300 1.58 M B -0.0506
#> 7 -0.130 2.00 M B -0.238
#> 8 -0.240 4.58 M B -0.0426
#> 9 0.590 0. F A NA
#> 10 1.97 1.58 F A 0.873
#> 11 2.26 2.00 F A 0.690
#> 12 1.89 4.58 F A -0.143
#> 13 0.590 0. M A NA
#> 14 1.97 1.58 M A 0.873
#> 15 2.26 2.00 M A 0.690
#> 16 1.89 4.58 M A -0.143
由reprex package创建于2018-09-03 (v0.2.0)。
https://stackoverflow.com/questions/52141438
复制