基于Dataset B的ID复制Dataset A行并追加的R语言技术需求
Hey there, let's tackle this problem where you need to copy rows from Dataset A that match the IDs in Dataset B, then append those copied rows to the end of Dataset A. Here's how to do it with both base R and the tidyverse (dplyr) approach:
Step 1: Define Your Original Datasets
First, let's set up the initial datasets as you provided:
# Dataset A dataA <- data.frame( id = as.character(1:10), name = c("bob", "ryan", "sean", "brock", "kobe", "andy", "andrew", "stephanie", "emma", "monica"), place = c(rep("central",3), rep("western",3), rep("eastern",4)) ) # Dataset B data_2 <- data.frame(id_2 = c('1', '3', '5'))
Step 2: Base R Solution
If you prefer using base R without extra packages, this straightforward method works perfectly:
# Filter rows in dataA where id matches any ID in data_2 matching_rows <- dataA[dataA$id %in% data_2$id_2, ] # Append the matching rows to the original dataA dataA_updated <- rbind(dataA, matching_rows)
Step 3: Tidyverse (dplyr) Solution
For a more readable, pipe-based workflow, use the dplyr package:
library(dplyr) # Filter matching rows and append to dataA in one concise step dataA_updated <- dataA %>% bind_rows(filter(., id %in% data_2$id_2))
Verify the Result
Both methods will generate exactly the dataset you're expecting. If you print dataA_updated, you'll see the original 10 rows followed by the copied rows for IDs 1, 3, and 5—matching your desired output perfectly.
内容的提问来源于stack exchange,提问作者C_Mu

