基于条件的单列求和:按Coins区间实现对应列数值求和
Got it! Let's figure out how to sum the Enrollment values based on those three Coins conditions (greater than 20, equal to 20, less than 20) in R. I’ll walk you through a couple of easy methods, using your sample data so you can test it right away.
First, let's recreate your sample dataset so we can work with it:
df <- data.frame( Plan = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"), Year = c(2018, 2014, 2012, 2017, 2018, 2018, 2018, 2016, 2014, 2017), Coins = c(20, 15, 30, 30, 5, 20, 20, 20, 10, 20), Copay = c(10, 5, 0, 10, 10, 0, 0, 10, 3, 7), Enrollment = c(200, 100, 50, 350, 400, 150, 200, 800, 250, 550) )
Method 1: Using dplyr (Tidyverse)
If you’re already using the tidyverse (a common set of R packages for data manipulation), this method is super readable. We’ll create a grouping column with case_when(), then sum the enrollment values per group:
library(dplyr) enrollment_sums <- df %>% # Create a column to label each row's Coins group mutate(coins_group = case_when( Coins > 20 ~ "Coins > 20", Coins == 20 ~ "Coins = 20", Coins < 20 ~ "Coins < 20" )) %>% # Group by the new label column group_by(coins_group) %>% # Calculate total enrollment for each group summarise(total_enrollment = sum(Enrollment)) # View the result print(enrollment_sums)
Method 2: Base R (No External Packages)
If you don’t want to install extra packages, base R has a few options. Here’s the most straightforward way to calculate each sum individually and combine them into a clean result:
# Calculate sums for each condition sum_coins_gt20 <- sum(df$Enrollment[df$Coins > 20]) sum_coins_eq20 <- sum(df$Enrollment[df$Coins == 20]) sum_coins_lt20 <- sum(df$Enrollment[df$Coins < 20]) # Combine into a data frame for easy reading enrollment_sums <- data.frame( coins_group = c("Coins > 20", "Coins = 20", "Coins < 20"), total_enrollment = c(sum_coins_gt20, sum_coins_eq20, sum_coins_lt20) ) print(enrollment_sums)
Alternative Base R: Using tapply()
If you prefer a more concise base R approach, tapply() can group and sum in one line:
enrollment_sums <- tapply( df$Enrollment, # Define groups using cut() INDEX = cut(df$Coins, breaks = c(-Inf, 19, 20, Inf), labels = c("Coins < 20", "Coins = 20", "Coins > 20")), FUN = sum ) # Convert to data frame if you want a tabular format enrollment_sums <- as.data.frame(enrollment_sums) print(enrollment_sums)
All these methods will give you the same result for your sample data:
Coins > 20: 400 (50 + 350)Coins = 20: 1900 (200 + 150 + 200 + 800 + 550)Coins < 20: 750 (100 + 400 + 250)
内容的提问来源于stack exchange,提问作者NewToThisRThing

