R语言代码优化:将行号整合到结果中
R语言代码优化:将行号整合到结果中
本文将介绍如何修改R语言代码,将每次抽取的行的序号整合到最后的结果中去,以便了解哪些行参与了求和运算。
原始代码:
library(openxlsx)
library(purrr)
library(dplyr)
data <- iris[1:13, 1:2]
data
Sepal.Length <- data$Sepal.Length
res_list1 <- list()
for (sel_n in 3:13) {
result <- data.frame(
Combination = sel_n,
Sum = combn(Sepal.Length, sel_n, FUN = sum)
)
res_list1[[sel_n]] <- result
}
res1 <- bind_rows(res_list1)
修改后的代码:
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函数将结果整合成一个数据框。
通过上述修改,我们可以方便地知道每个组合的求和结果是哪些行的数值之和。
原文地址: https://www.cveoy.top/t/topic/p4qz 著作权归作者所有。请勿转载和采集!