如何在R语言中合并两个CSV文件并匹配数据,将CSV2的episode review列按剧集名关联至CSV1
Merge Episode Data with Matching Reviews in R
Got it, here's a straightforward, reliable way to combine your two CSV files so the episode reviews from CSV2 get correctly paired with the corresponding entries in CSV1:
Step 1: Load Required Libraries
We’ll use dplyr (included in the tidyverse collection) for seamless data merging. Either library works, but tidyverse gives you extra handy tools for data wrangling:
# Load tidyverse (includes dplyr for merging functionality) library(tidyverse) # Alternatively, load just dplyr if you don't need other tidyverse tools: # library(dplyr)
Step 2: Import Your CSV Files
First, read both datasets into R as data frames:
# Read your main episode dataset (CSV1) df1 <- read.csv('NewEpisodes.csv', header = TRUE) # Read the dataset containing episode reviews (CSV2) df2 <- read.csv('episodesReview.csv', header = TRUE)
Step 3: Merge the Data Frames
Use left_join() to combine the two datasets. We match on both Episode.Name and Show.Name to avoid mismatches (critical if different shows share episode titles):
# Merge df1 with df2, keeping all rows from df1 and adding matching reviews merged_episodes <- df1 %>% left_join(df2, by = c("Episode.Name", "Show.Name"))
Quick Breakdown of the Merge:
left_join()ensures every entry from your original episode data (df1) is preserved in the final result.- Reviews from
df2are only added where there’s an exact match on both the episode name and show name. - If an episode in
df1has no corresponding review indf2, the review column will showNA(you can clean or fill these later if needed).
If you want to save the merged result back to a CSV file:
# Export merged data to a new CSV (exclude row numbers with row.names = FALSE) write.csv(merged_episodes, 'MergedEpisodesWithReviews.csv', row.names = FALSE)
内容的提问来源于stack exchange,提问作者psmadness
相关产品推荐
相关产品推荐

