[英]How do I append an entire column to the end of another column in r?
I have col3 and col4, both have 5000 rows.我有 col3 和 col4,都有 5000 行。 I want to make a new column that has 10,000 rows, the first 5000 being col3 and the second 5000 being col4.
我想创建一个有 10,000 行的新列,第一个 5000 是 col3,第二个 5000 是 col4。 Or if it's easier they do not actually need to be in order.
或者,如果它更容易,它们实际上并不需要按顺序排列。
are these vestors?这些是委托人吗? A reproducible example would be nice, but some variation of this should work
一个可重现的例子会很好,但是这个的一些变化应该可以工作
new_col <- rbind(col3,col4)
Let's first create a sample dataset (as you haven't given)让我们首先创建一个示例数据集(因为您还没有给出)
set.seed(50)
df <- data.frame(col3 = runif(500),
col4 = runif(500))
> head(df)
col3 col4
1 0.70872710 0.1396443
2 0.43765986 0.6179266
3 0.20000490 0.8179890
4 0.76706599 0.2320035
5 0.51316189 0.9072317
6 0.04470388 0.2108911
Nor proceed to append like this ( Note you have to create this is as new data frame as previous one has lesser rows than required )也不要像这样继续到 append (请注意,您必须创建这是作为新数据框的新数据框,因为前一个数据框的行数少于所需的行数)
df_new <- data.frame(new_col = c(df$col3, df$col4))
> (tibble(df_new))
# A tibble: 1,000 x 1
new_col
<dbl>
1 0.709
2 0.438
3 0.200
4 0.767
5 0.513
6 0.0447
7 0.700
8 0.646
9 0.0420
10 0.108
# ... with 990 more rows
In case, you have other columns in data which you have to preserve along with this append, then proceed as follows如果您在数据中还有其他列必须与此 append 一起保留,请执行以下操作
set.seed(50)
df <- data.frame(id = 1:500,
col3 = runif(500),
col4 = runif(500))
(tibble(df))
# A tibble: 500 x 3
id col3 col4
<int> <dbl> <dbl>
1 1 0.540 0.0111
2 2 0.522 0.509
3 3 0.371 0.803
4 4 0.526 0.274
5 5 0.342 0.922
6 6 0.450 0.512
7 7 0.383 0.698
8 8 0.651 0.0556
9 9 0.491 0.748
10 10 0.677 0.728
# ... with 490 more rows
#Process of append
library(dplyr)
df %>% pivot_longer(cols = c(col3, col4)) %>% select(-name)
# A tibble: 1,000 x 2
id value
<int> <dbl>
1 1 0.540
2 1 0.0111
3 2 0.522
4 2 0.509
5 3 0.371
6 3 0.803
7 4 0.526
8 4 0.274
9 5 0.342
10 5 0.922
# ... with 990 more rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.