[英]How do I append an entire column to the end of another column in r?
我有 col3 和 col4,都有 5000 行。 我想創建一個有 10,000 行的新列,第一個 5000 是 col3,第二個 5000 是 col4。 或者,如果它更容易,它們實際上並不需要按順序排列。
這些是委托人嗎? 一個可重現的例子會很好,但是這個的一些變化應該可以工作
new_col <- rbind(col3,col4)
讓我們首先創建一個示例數據集(因為您還沒有給出)
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
也不要像這樣繼續到 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
如果您在數據中還有其他列必須與此 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.