假设数据框为df,其中有一列为'value',可以按照如下方式进行操作:

library(dplyr)

# 定义计算斜率的函数
calc_slope <- function(x) {
  if (length(x) == 4) {
    slope <- (x[4] - x[1]) / 30
  } else {
    slope <- (x[length(x)] - x[1]) / ((length(x) - 1) * 30)
  }
  return(slope)
}

# 按照顺序每四行分组计算斜率并追加到数据框
df <- df %>%
  group_by(group = (row_number() - 1) %/% 4) %>%
  mutate(slope = calc_slope(na.omit(value))) %>%
  ungroup() %>%
  select(-group)

# 将计算的斜率追加到每次计算的第一行后面
df$slope[seq(1, nrow(df), 4)] <- c(df$slope[1], rep(NA, nrow(df) %/% 4 - 1))

# 将空值替换成NA
df[df == ''] <- NA

原文地址: https://www.cveoy.top/t/topic/l4BP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录