RStudio中不同长度数据集求和:为数据集添加Profit列
Hey there! Since you're new to R, let's break this down simply—you don't need aggregate here (that's for grouping and summarizing data, not matching rows between datasets). The right approach is to join your two datasets first so you can access the Sales values alongside Upkeep in Account_Scenarios, then calculate the Profit column. Here are two easy methods, including one with a beginner-friendly package:
dplyr (Recommended for New R Users) dplyr uses readable, pipe-based syntax that's easier to follow for beginners. First, we'll connect Sales to Account_Scenarios using shared columns (like a person's name and scenario ID), then compute the new column.
Step 1: Install and load the package (if you haven't already)
install.packages("dplyr") library(dplyr)
Step 2: Join datasets and calculate Profit
Replace c("Person", "Scenario") with the actual column names that exist in both datasets (these are the keys that match each person to their scenario-specific sales data):
# Join Sales to Account_Scenarios, keeping all rows from Account_Scenarios Account_Scenarios <- Account_Scenarios %>% left_join(Sales, by = c("Person", "Scenario")) %>% # Calculate Profit using the formula: Profit = Sales + Upkeep mutate(Profit = Sales + Upkeep)
If you prefer not to install new packages, you can use base R's merge() function to combine the datasets, then add the Profit column directly.
# Merge the two datasets, keeping all rows from Account_Scenarios Account_Scenarios <- merge(Account_Scenarios, Sales, by = c("Person", "Scenario"), all.x = TRUE) # Add the Profit column Account_Scenarios$Profit <- Account_Scenarios$Sales + Account_Scenarios$Upkeep
- Double-check your join keys: Make sure the columns you use in
by = ...exist in both datasets and uniquely link each row inAccount_Scenariosto the correctSalesvalue (e.g., if you only usePersonwithoutScenario, you'll match the wrong sales data for people in multiple scenarios). - Handle missing values: If some rows in
Account_Scenariosdon't have a matching entry inSales, theSalescolumn will showNA, andProfitwill also beNA. To fix this, replace missing sales values with 0 (or another default) using:# With dplyr Account_Scenarios <- Account_Scenarios %>% mutate(Profit = coalesce(Sales, 0) + Upkeep) # With base R Account_Scenarios$Sales[is.na(Account_Scenarios$Sales)] <- 0 Account_Scenarios$Profit <- Account_Scenarios$Sales + Account_Scenarios$Upkeep
内容的提问来源于stack exchange,提问作者Dinks123

