You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言报错:longer object length is not a multiple of shorter object length求助

生存函数计算方差时的长度不匹配错误排查

我尝试用已计算好的生存函数计算方差,实现代码如下,但运行时出现longer object length is not a multiple of shorter object length错误,求排查原因:

survfunc <- cancer_obs$KM 
B <- 100
N <- 1000

# Replace P(T > t) with the appropriate survival function or probability distribution function for T

integrand1 <- function(t) {survfunc}  
midpoint_rule1 <- function(a, b, n) {
  h <- (b - a) / n
  sum(integrand1(a + h/2 + h * (0:(n-1)))) * h
}

integrand2 <- function(t) {2*t*survfunc}
midpoint_rule2 <- function(a, b, n) {
  h <- (b - a) / n
  sum(integrand2(a + h/2 + h * (0:(n-1)))) * h
}

approx_integral1 <- midpoint_rule1(0, B, N)
approx_integral2 <- midpoint_rule2(0, B, N)

var_estimation <- approx_integral2 - (approx_integral1)^2 

错误原因

  • survfunc是KM生存曲线对象(通常是survfit()返回的结果),不是可直接参与逐元素运算的函数或向量。当midpoint_rule生成长度为1000的t向量传入积分函数时,survfunc的长度与t不匹配,R在尝试逐元素运算时就会抛出长度不兼容的错误。
  • 你的积分函数直接返回survfunc,没有根据输入的t值计算对应的生存概率S(t),完全不符合积分逻辑——积分需要对每个t点的S(t)或2*t*S(t)求和。

修正后的代码

# 假设cancer_obs$KM是survfit得到的生存分析结果
surv_obj <- cancer_obs$KM
B <- 100
N <- 1000

# 将KM曲线转换为可根据t值计算生存概率的阶梯函数
surv_fun <- stepfun(surv_obj$time, c(1, surv_obj$surv))

# 定义第一个积分函数:计算每个t对应的生存概率S(t)
integrand1 <- function(t) { surv_fun(t) }  
midpoint_rule1 <- function(a, b, n) {
  h <- (b - a) / n
  t_points <- a + h/2 + h * (0:(n-1))
  sum(integrand1(t_points)) * h
}

# 定义第二个积分函数:计算2*t*S(t)
integrand2 <- function(t) { 2 * t * surv_fun(t) }
midpoint_rule2 <- function(a, b, n) {
  h <- (b - a) / n
  t_points <- a + h/2 + h * (0:(n-1))
  sum(integrand2(t_points)) * h
}

approx_integral1 <- midpoint_rule1(0, B, N)
approx_integral2 <- midpoint_rule2(0, B, N)

var_estimation <- approx_integral2 - (approx_integral1)^2 

修正说明

  • 用stepfun()将KM生存曲线转换为阶梯函数surv_fun,该函数可接受任意长度的t向量,返回对应每个t的生存概率,保证运算时长度匹配。
  • 积分函数中明确根据输入的t向量调用surv_fun(t),生成与t长度一致的生存概率向量,解决逐元素运算的长度问题。
  • 单独提取t_points变量,简化代码逻辑,避免重复计算。

内容的提问来源于stack exchange,提问作者trying

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:27:53