首页 文章

dplyr - 使用列中值的累积和来自其他列的值的平均值从数据框中分隔行

提问于
浏览
1

我没有根据所选行的列的累积和以及来自另一列的值的平均值来从数据帧中分离行的确切想法 .

样本数据框:

ID Weight Units
16-1791-9731    299    50
16-1791-9732    301    72
16-1791-9730    301    34
16-1787-9720    296    78
16-1787-9719    297    98
16-1787-9717    300    98
16-1787-9718    301    98
16-1782-9700    297    74
16-1782-9699    299    74
16-1782-9703    301   104
16-1782-9702    303   140
16-1785-9710    298    77
16-1785-9708    298    77
16-1785-9711    299   200
16-1785-9709    300   200
16-1265-7695    299    72

Image of dataframe

例如,如何将2组4行作为单独的数据帧拉出,其中 Units 平均值为61,累计和为 weight ,范围为800到1100.选择到新数据帧的行也应从主df中删除 .

实际工作数据框 - enter link description here我试图使用更接近前面指定条件的最佳方法从数据框中提取行 . (累计重量在800到1100之间,选定的PotOG平均值在400(400到420之间))

工作步骤1)识别3-4行(约为选择权重范围介于800和1100之间)2)确定PotOG的平均值(来自加权平均值)3)识别PotOG范围在400和420之间.4)最合适的行作为一个簇被拉出到新的数据帧(也从master中删除.5)重复进程以进一步请求

有什么建议在dplyr中实现这一目标吗?

1 回答

  • 1

    不完全确定这是否是您正在寻找的,因为您没有显示预期的输出,您的标准和输入数据提供的零个案例符合所列条件 . 但是,这是我能想出的问题的一种方法 .

    # Get all possible combinations of four rows
    combn_df <- as.data.frame(t(combn(1:nrow(df), 4, sort)))
    
    # Test each combination of four rows for both conditions
    combn_df$weightsInRange <- apply(combn_df, 1, function(x) between(sum(df$Weight[x]), 800, 1100))
    combn_df$unitsMean61 <- apply(combn_df, 1, function(x) mean(df$Units[x[1:4]]) == 61)
    
    # Select combinations of rows that meet both conditions
    combn_df <- combn_df[combn_df$weightsInRange & combn_df$unitsMean61, ]
    
    # Extract two sets of four rows from original DF into two separate data frames
    apply(combn_df[1:2, ], 1, function(x) df[x[1:4], ])
    

相关问题