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

R语言:不新增列且不使用rbind类函数合并两个data.frame

Hey there! Got you covered with a solution that avoids the restricted functions while stacking all rows from your two data frames—no extra columns added, just pure row stacking:

First, let's set up your original data frames as you specified:

one <- mtcars[1:4, ]
two <- mtcars[1:7, ]

Now here's the trick: we'll build the combined data frame by concatenating the corresponding columns from both datasets, then wrapping them back into a data frame. This skips any of the forbidden row-binding functions entirely:

combined <- data.frame(lapply(one, function(col) {
  # Grab the matching column from 'two' using the current column's name
  matching_col <- two[[names(col)]]
  # Concatenate the two column vectors
  c(col, matching_col)
}))

How this works:

  • We use lapply() to loop through every column in one.
  • For each column, we fetch the exact same column from two (using the column name to ensure a match).
  • We concatenate the values from one's column and two's column into a single vector.
  • Finally, data.frame() takes all these concatenated columns and assembles them into the full combined dataset.

If you print the first few rows, you'll see exactly the stacked result you're looking for:

> head(combined)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Mazda RX4.1       21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag.1   21.0   6  160 110 3.90 2.875 17.02  0  1    4    4

内容的提问来源于stack exchange,提问作者user3698773

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:56:13