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

基于R语言tidyverse实现变长度向量向量化求和计算y值

解决嵌套矩阵索引问题计算y值

问题根源

你之前的报错是因为误用了c_across()——这个函数用于跨数据框的列取值,但你的delta是每个单元格中存储的向量/矩阵,并非数据框的独立列,因此无法通过c_across对其索引。

修正后的代码

library(tidyverse)
library(extraDistr)
n <- 100
x_max <- 4

set.seed(1)
data <- 
    tibble(
        id = 1:100,
        beta = rnorm(100, mean = 0, sd = 1/(x_max - 1)),
        delta = cbind(0, rdirichlet(n, rep(1, x_max - 1)))
    ) %>% 
    expand_grid(x = 1:x_max)

# 计算y值的正确代码
data_result <- data %>%
    rowwise() %>%
    mutate(
        y = beta * sum(delta[1:x])
    ) %>%
    ungroup() # 若后续不需要逐行操作,可取消rowwise状态

# 查看前10行结果
data_result %>% slice(1:10)

结果展示

运行后会得到符合预期的输出:

# A tibble: 10 × 5
      id    beta delta[,1]   [,2]    [,3]   [,4]     x        y
   <int>   <dbl>     <dbl>  <dbl>   <dbl>  <dbl> <int>    <dbl>
 1     1 -0.209          0 0.169  0.170   0.661      1  0      
 2     1 -0.209          0 0.169  0.170   0.661      2 -0.0352 
 3     1 -0.209          0 0.169  0.170   0.661      3 -0.0708 
 4     1 -0.209          0 0.169  0.170   0.661      4 -0.209  
 5     2  0.0612         0 0.0962 0.00297 0.901      1  0      
 6     2  0.0612         0 0.0962 0.00297 0.901      2  0.00589
 7     2  0.0612         0 0.0962 0.00297 0.901      3  0.00607
 8     2  0.0612         0 0.0962 0.00297 0.901      4  0.0612 
 9     3 -0.279          0 0.241  0.714   0.0451     1  0      
10     3 -0.279          0 0.241  0.714   0.0451     2 -0.0671 

关键说明

在rowwise()环境下,每个行的delta是独立的长度为x_max的向量,直接用delta[1:x]即可提取前x个元素,求和后与beta相乘就得到公式$y=\beta\sum_{i=1}^x\delta_i$的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:54:56