You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Dataset B的ID复制Dataset A行并追加的R语言技术需求

Append Matching Rows to Dataset A Based on Dataset B IDs

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:03:55