gpt4 book ai didi

r - 查找选定列中多个点的斜率

转载 作者:行者123 更新时间:2023-12-04 10:54:31 25 4
gpt4 key购买 nike

给定以下数据框:

structure(list(`-5` = c(0, 1, 0, 0, 9, 22), `-4` = c(1, 3, 0, 
0, 1, 17), `-3` = c(1, 3, 0, 0, 0, 12), `-2` = c(1, 3, 0, 0,
2, 10), `-1` = c(0, 0, 0, 4, 3, 9), `0` = c(0, 1, 0, 2, 2, 21
), `1` = c(0, 1, 1, 7, 1, 21), `2` = c(1, 0, 1, 2, 1, 10), `3` = c(0,
9, 0, 6, 1, 12), `4` = c(0, 2, 0, 5, 0, 18), `5` = c(0, 0, 0,
3, 0, 23)), .Names = c("-5", "-4", "-3", "-2", "-1", "0", "1",
"2", "3", "4", "5"), row.names = c(NA, 6L), class = "data.frame")

# -5 -4 -3 -2 -1 0 1 2 3 4 5
#1 0 1 1 1 0 0 0 1 0 0 0
#2 1 3 3 3 0 1 1 0 9 2 0
#3 0 0 0 0 0 0 1 1 0 0 0
#4 0 0 0 0 4 2 7 2 6 5 3
#5 9 1 0 2 3 2 1 1 1 0 0
#6 22 17 12 10 9 21 21 10 12 18 23

我希望 R 为我提供 -5:-1 列每行中所有数据点的斜率。基本上是基于这 5 个数据点的线性回归趋势线的斜率。然后是 1:5 列的所有数据点的第二个斜率。第 0 年被忽略。

基本上这就是它的样子(使用 Excel 计算的最后两列):

structure(list(`-5` = c(0, 1, 0, 0, 9, 22), `-4` = c(1, 3, 0, 
0, 1, 17), `-3` = c(1, 3, 0, 0, 0, 12), `-2` = c(1, 3, 0, 0,
2, 10), `-1` = c(0, 0, 0, 4, 3, 9), `0` = c(0, 1, 0, 2, 2, 21
), `1` = c(0, 1, 1, 7, 1, 21), `2` = c(1, 0, 1, 2, 1, 10), `3` = c(0,
9, 0, 6, 1, 12), `4` = c(0, 2, 0, 5, 0, 18), `5` = c(0, 0, 0,
3, 0, 23), `Negative Years` = c(0, -2, 0, 0.8, -1.1, -3.3), `Positive Years` = c(-0.1,
0, -0.3, -0.5, -0.3, 1.2)), .Names = c("-5", "-4", "-3", "-2",
"-1", "0", "1", "2", "3", "4", "5", "Negative Years", "Positive Years"
), row.names = c(NA, 6L), class = "data.frame")

# -5 -4 -3 -2 -1 0 1 2 3 4 5 Negative Years Positive Years
#1 0 1 1 1 0 0 0 1 0 0 0 0.0 -0.1
#2 1 3 3 3 0 1 1 0 9 2 0 -2.0 0.0
#3 0 0 0 0 0 0 1 1 0 0 0 0.0 -0.3
#4 0 0 0 0 4 2 7 2 6 5 3 0.8 -0.5
#5 9 1 0 2 3 2 1 1 1 0 0 -1.1 -0.3
#6 22 17 12 10 9 21 21 10 12 18 23 -3.3 1.2

最佳答案

这是统计学家(不是数据科学家)会做的事情。

让你的数据框为dat

Y <- t(dat)  ## response matrix
t <- -5:5 ## time stamps
id <- c(rep("-", 5), NA, rep("+", 5)) ## group index (factor)
fit <- lm(Y ~ t * id) ## mlm
m <- coef(fit)[c(2, 4), ] ## coefficient matrix
m[2, ] <- m[2, ] + m[1, ] ## reverse contrast
round(t(m), 2)

# t t:id+
#1 0.0 -0.1
#2 -0.2 0.0
#3 0.0 -0.3
#4 0.8 -0.5
#5 -1.1 -0.3
#6 -3.3 1.2

将列名更改为您想要的。

关于r - 查找选定列中多个点的斜率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51180159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com