gpt4 book ai didi

r - 按组对数据框中指定列的所有可能的从左到右对角线求和?

转载 作者:行者123 更新时间:2023-12-01 10:17:45 26 4
gpt4 key购买 nike

假设我有这样的东西:

df<-data.frame(group=c(1, 1,2, 2, 2, 4,4,4,4,6,6,6), 
binary1=c(1,0,1,0,0,0,0,0,0,0,0,0),
binary2=c(0,1,0,1,0,1,0,0,0,0,1,1),
binary3=c(0,0,0,0,1,0,1,0,0,0,0,0),
binary4=c(0,0,0,0,0,0,0,1,0,0,0,0))

我想沿着组内所有可能的从左到右的对角线求和(即组 1、2、4 和 6)并返回最大总和。这也在一个数据框中,所以我想指定只对 binary1-binary4 求和。有人知道这是否可能吗?

这是我想要的输出:

   group binary1 binary2 binary3 binary4 want
1 1 1 0 0 0 2
2 1 0 1 0 0 2
3 2 1 0 0 0 3
4 2 0 1 0 0 3
5 2 0 0 1 0 3
6 4 0 1 0 0 3
7 4 0 0 1 0 3
8 4 0 0 0 1 3
9 4 0 0 0 0 3
10 6 0 0 0 0 1
11 6 0 1 0 0 1
12 6 0 1 0 0 1

我已经圈出我想在这张图片中为第 4 组求和的“对角线”作为示例:

enter image description here

最佳答案

这是另一种解决方案,我们使用 rowcol 索引来获取所有可能的对角线组合。使用 by 按组拆分并将其与原始数据框合并

max_diag <- function(x) max(sapply(split(as.matrix(x), row(x) - col(x)), sum))

merge(df, stack(by(df[-1], df$group, max_diag)), by.x = "group", by.y = "ind")

# group binary1 binary2 binary3 binary4 values
#1 1 1 0 0 0 2
#2 1 0 1 0 0 2
#3 2 1 0 0 0 3
#4 2 0 1 0 0 3
#5 2 0 0 1 0 3
#6 4 0 1 0 0 3
#7 4 0 0 1 0 3
#8 4 0 0 0 1 3
#9 4 0 0 0 0 3
#10 6 0 0 0 0 1
#11 6 0 1 0 0 1
#12 6 0 1 0 0 1

关于r - 按组对数据框中指定列的所有可能的从左到右对角线求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59538273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com