修改后的代码如下:

library(openxlsx)
library(purrr)
library(dplyr)

data <- iris[1:13, 1:2]
data$RowNum <- 1:13 # 添加行号列
data

Sepal.Length <- data$Sepal.Length

res_list1 <- list()

for (sel_n in 3:13) {
  
  result <- data.frame(
    Combination = sel_n,
    RowNums = combn(data$RowNum, sel_n), # 添加行号的组合
    Sum = combn(Sepal.Length, sel_n, FUN = sum)
  )
  res_list1[[sel_n]] <- result
}

res1 <- bind_rows(res_list1)

修改后的代码在data数据框中添加了一列RowNum,表示每行的行号。在计算每个组合的和时,使用combn函数获取了每次抽取的行的行号,将其保存在RowNums列中。这样就能知道抽取的哪些行求和了。最后通过bind_rows函数将结果整合成一个数据框

对下面R语言代码进行修改libraryopenxlsxlibrarypurrrlibrarydplyrdata - iris113 12dataSepalLength - data$SepalLengthres_list1 - listfor sel_n in 313 result - dataframe Combination = sel_n Sum = combnSepal

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

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