![](/img/trans.png)
[英]Duplicating records in R and inputting a new column with a different value for each duplicated record
[英]Duplicating a column and placing right next to that duplicated column
我想復制一列,但我看到的所有示例都在數據框的末尾有重復的列 go,但我希望它緊挨着復制的列,而是將數據的 rest 向下推。
例如:我有 DF1
名稱 | 鑰匙 | BCD12A | ACA1 | 敏捷2 |
---|---|---|---|---|
X_1_group1 | 測試1234 | 10 | 10 | 8個 |
X_2_group1 | 測試4553 | 8個 | 7 | 4個 |
X_2_group2 | 測試3341 | 5個 | 5個 | 5個 |
X_2_group1 | 測試2142 | 5個 | 6個 | 8個 |
X_1_group2 | 測試4722 | 6個 | 7 | 4個 |
復制這個,我會在第二列之后有另一列復制“DF$Key”。 任何關於這樣做的建議將不勝感激!
# DF1
Name <- c("X_1_group1", "X_2_group1", "X_2_group2", "X_2_group1", "X1_group2")
Key <- c("test1234", "test4553", "test3341", "test2142", "test4722")
BCD12A <- c(10, 8, 5, 5, 6)
ACA1 <- c(10, 7, 5, 6, 7)
DEX2 <- c(8, 4, 5, 8, 4)
DF1 <- data.frame(Name, Key, BCD12A, ACA1, DEX2)
我們可以使用帶有.after
或.before
的mutate
來創建列。 .after/.before
的輸入可以是不帶引號/帶引號的列名或數字列索引
library(dplyr)
DF1 <- DF1 %>%
mutate(Key2 = Key, .after = Key)
-輸出
DF1
Name Key Key2 BCD12A ACA1 DEX2
1 X_1_group1 test1234 test1234 10 10 8
2 X_2_group1 test4553 test4553 8 7 4
3 X_2_group2 test3341 test3341 5 5 5
4 X_2_group1 test2142 test2142 5 6 8
5 X_1_group2 test4722 test4722 6 7 4
這是一個基本的 R 版本:
DF1$Key2 <- DF1$Key
col_order <- c(1:2, 6, 3:5)
DF1[, col_order]
Name Key Key2 BCD12A ACA1 DEX2
1 X_1_group1 test1234 test1234 10 10 8
2 X_2_group1 test4553 test4553 8 7 4
3 X_2_group2 test3341 test3341 5 5 5
4 X_2_group1 test2142 test2142 5 6 8
5 X1_group2 test4722 test4722 6 7 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.