如何对数据帧向量中的特定级别求和?

问题描述 投票:0回答:1

我有一个包含三种情况的数据框,其中两种代表满足,一种代表未满足。我需要根据情况列的级别(部分满足和完全满足)添加第 n 列。我可以根据条件创建一个新列并生成两个级别:满足和未满足,但我认为没有必要。

这是我第一次尝试,但没有成功:

SITUATION <- rep(c("UNMET", "FULLY MET", "PARTIALLY MET"),8)
BLOCK <- rep( 1:8, each = 3, len = 24 )

TOTAL <- floor(runif(24, min=2, max=32))

df <- as.data.frame(cbind(SITUATION, BLOCK, TOTAL))

agg_df <- aggregate(df$TOTAL, by=list(grepl(c("FULLY MET", "PARTIALLY MET"),
                    df$ATENDENCE)), FUN=sum)
Error in aggregate.data.frame(as.data.frame(x), ...) : 
arguments must have the same length    
In addition: Warning message:
In grepl(c("FULLY MET", "PARTIALLY MET"), df$ATENDENCE) :
argument 'pattern' has length > 1 and only the first element will be used

r dataframe aggregate
1个回答
0
投票
set.seed(123)
SITUATION <- rep(c("UNMET", "FULLY MET", "PARTIALLY MET"),8)
BLOCK <- rep( 1:8, each = 3, len = 24 )
TOTAL <- floor(runif(24, min=2, max=32))

df <- data.frame(SITUATION, BLOCK, TOTAL)
library(dplyr, warn.conflicts = F)

df %>% 
  mutate(SITUATION = ifelse(grepl("UNMET", SITUATION), "UNMET", "MET")) %>% 
  summarise(across(where(is.numeric), sum), .by = c(SITUATION, BLOCK))
#>    SITUATION BLOCK TOTAL
#> 1      UNMET     1    10
#> 2        MET     1    39
#> 3      UNMET     2    28
#> 4        MET     2    33
#> 5      UNMET     3    17
#> 6        MET     3    46
#> 7      UNMET     4    15
#> 8        MET     4    45
#> 9      UNMET     5    22
#> 10       MET     5    24
#> 11     UNMET     6    28
#> 12       MET     6    12
#> 13     UNMET     7    11
#> 14       MET     7    58
#> 15     UNMET     8    22
#> 16       MET     8    52

创建于 2023-09-21,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.